Everthing seems to work except inserting data stmt.
I've added closing the connection and adding closing the statement.
$error = $user = $pass = "";
if (isset($_SESSION['user'])) destroySession();
if (isset($_POST['user']))
{
$user = sanitizeString($_POST['user']);
$pass = sanitizeString($_POST['pass']);
if ($user == "" || $pass == "")
$error = 'Not all fields were entered<br><br>';
else
{
$stmt = $connection->prepare('SELECT * FROM members WHERE user=?');
$stmt->bind_param('s', $user);
$stmt->execute();
$result = $stmt->get_result();
if ($result->num_rows)
$error = 'That username already exists<br><br>';
else
{
$hashedPwd = password_hash($pass, PASSWORD_DEFAULT);
$stmt = $connection->prepare("INSERT INTO members (user, pass) VALUES (?,?)");
$stmt->bind_param("ss", $user, $hashedPwd);
$stmt->execute;
$stmt->close();
die('<h4>Account created</h4>Please Log in.</div></body></html>');
}
}
}
$connection->close();
I can expect the code to recognize if a user exists. However, I can not expect the database to be updated with a new user.
Placing error_reporting(E_ALL); at the top of the page will show that there is problem with the $stmt->execute;
$stmt->execute; should be stmt->execute();
Related
I'm creating a back end to my website and running into issues with the login user part.
The user registration into the database is made with the password_hash function using the code below:
UserReg.php :
<?php
require_once 'db.php';
$mysqli = new mysqli($host, $user, $password, $dbname);
if($mysqli -> connect_error) {
die($mysqli -> connect_erro);
}
$username = "userF";
$password = "somePass";
$token = password_hash("$password", PASSWORD_DEFAULT);
add_user($mysqli,$username, $token);
function add_user($mysqli,$username, $token) {
$query = $mysqli->prepare("INSERT INTO users(username, password) VALUES
(?,?)");
$query->bind_param('ss',$username, $token);
$query->execute();
$result = $query->get_result();
if(!$result) {
die($mysqli->error);
}
$query->close();
}
My login form skips to a blank page even when i insert my username and password. Doesn't even go to the login error message.
Login.php
<?php
include 'db.php';
$username = $_POST['user'];
$pwd = $_POST['password'];
$sql = "SELECT password FROM users WHERE username = ?";
$stmt = $mysqli->prepare($sql);
$stmt->execute();
$stmt->bind_result($pass);
while ($result = $stmt->num_rows()) {
if($stmt->password_verify($pwd, $result)) {
echo "Your username or password is incorrect";
} else {
header("Location: Menu.php");
}
}
What am i missing?
Appreciate your help.
I think you need to take a look at password_verify how it works.
$username = $_POST['user'];
$pwd = $_POST['password'];
$sql = "SELECT username, password FROM users WHERE username = ?";
$stmt = $mysqli->prepare($sql);
$stmt->bind_param('s', $username);
$stmt->execute();
$stmt->bind_result($username, $password);
$stmt->store_result();
if ($stmt->num_rows == 1) { //To check if the row exists
if ($stmt->fetch()) { //fetching the contents of the row
if (password_verify($pwd, $password)) {
$_SESSION['username'] = $username;
echo 'Success!';
exit();
} else {
echo "INVALID PASSWORD!";
}
}
} else {
echo "INVALID USERNAME";
}
$stmt->close();
I have managed to write a php script that checks if a username already exists in the database and only adds a new user if it does not already exist.
This is my php script:
<?php
require "init.php";
if(isset($_POST['username']) && isset($_POST['forename']) && isset($_POST['surname']) && isset($_POST['password'])){
$username = $_POST['username'];
$forename = $_POST['forename'];
$username = $_POST['surname'];
$password = $_POST['password'];
$stmt = "SELECT username FROM users WHERE username = ?";
$result = $dbcon -> prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->bind_result($username);
if($result->fetch()){
echo "Can't add new user as it already exists!";
}
else{
$stmt_two = "INSERT INTO users (username, forename, surname, password)
VALUES(?, ?, ?, ?)";
$result_two = $dbcon -> prepare($stmt_two);
$result_two->bind_param('ssss', $username, $forename, $surname, $password);
$result_two->execute();
$result_two->close();
echo json_encode("Success");
}
}
?>
I believe the records are not being inserted or being inserted intermittently due to the fact that I have more than one prepared statement. If I just do the INSERT INTO statement on its' own with the SELECT FROM statement - the records are added almost instantly.
Why is this and what is wrong with my code?
Thanks
Just as I have said in the comments, don't over complicate and just check the number of rows found. No need to fetch anything. You're just checking if that user exists anyway.
$stmt = "SELECT username FROM users WHERE username = ?";
$result = $dbcon->prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->store_result();
if($result->num_rows() > 0) { // if it exists
} else {
// make your insertions
}
And another note:
isset can take multiple arguments:
if(isset($_POST['username'], $_POST['forename'], $_POST['surname'], $_POST['password'])) {
// and so on
}
Edit: Another flavor (using COUNT() of MySQL):
$stmt = "SELECT COUNT(username) FROM users WHERE username = ?";
$result = $dbcon->prepare($stmt);
$result->bind_param('s', $username);
$result->execute();
$result->bind_result($count);
$result->fetch();
if($count > 0) { // exists
} else {
// do something else
}
Can someone please take a look at this block of code? I am very new to the PDO method, for some reason this keeps causing a 500 error whenever I submit.
I have narrowed it down to this:
Could it be this part? $hash = $stmt['hash'];
if(empty($response['error'])){
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
// Bind the parameters to the query
$stmt->bindParam(':username', $username);
//Carry out the query
$stmt->execute();
$hash = $stmt['hash'];
$affectedRows = $stmt->rowCount(); // Getting affected rows count
if($affectedRows != 1){
$response['error'][] = "No User is related to the Username";
}
if(password_verify($password, $hash))
{
$_SESSION['username'] = $_POST['username'];
$_SESSION['userid'] = $stmt['ID'];
}
else
{
$response['error'][] = "Your password is invalid.";
}
}
If you need more info please ask I will be happy to supply anything I can.
You need to fetch the result of the query to have it accessible. I'm not sure this is your issue, I'd think $hash would just be set to Resource Id#x, not what you want but not a 500. Here's how to fetch (http://php.net/manual/en/pdostatement.fetch.php) though
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username"); // Prepare the query
// Bind the parameters to the query
$stmt->bindParam(':username', $username);
//Carry out the query
$stmt->execute();
//if you will only be getting back one result you dont need the while or hashes as an array
while($result = $stmt->fetch(PDO::FETCH_ASSOC)){
$hashes[] = $result['hash'];
}
Here's a thread on enabling error reporting PHP production server - turn on error messages
Also you don't have to bind to pass values with the PDO. You also could do
$stmt = $db->prepare("SELECT * FROM Login WHERE username= ?"); // Prepare the query
$stmt->execute(array($username));
Your code is really messy. Just to help you with start point:
if (empty($response['error'])) {
if (isset($_POST['username'])) {
$username = $_POST['username'];
$password = $_POST['password'];
$stmt = $db->prepare("SELECT * FROM Login WHERE username= :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
if ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
$hash = $row['hash'];
if(password_verify($password, $hash)) {
$_SESSION['username'] = $username;
$_SESSION['userid'] = $stmt['ID'];
} else {
$response['error'][] = "Your password is invalid.";
}
} else {
$response['error'][] = "No User is related to the Username";
}
} else {
$response['error'][] = "Username is not set!";
}
}
Hi, I am new to PHP and I am trying to write prepare statement for login but as given below code my query is not getting any row but getting field_count.
And if I put that
SELECT * FROM users WHERE UserName = 'DemoUser'
in direct database I am getting one row but here $stmt->num_rows is zero. What am I missing.
// in connections.php
$dbh = new mysqli($host, $username, $password, $database);
include('connections.php');
include('config.php');
include('comman_functions.php');
if(isset($_POST['password']) && $_POST['password']!=''
&& isset($_POST['username']) && $_POST['username']!=''
&& isset($_POST['location']) && $_POST['location']!='') {
$username = "DemoUser";
$stmt = $dbh->prepare("SELECT * FROM users WHERE UserName =? ");
$stmt->bind_param("s", $username);
$stmt->execute();
error_log($stmt->num_rows);
if($stmt->num_rows>0){
$row = $stmt->fetch();
error_log("logged in!!!");
$stmt->close();
} else {
$_SESSION['error'] = 'Invalid Username or Password';
header('Location:index.php');
}
} else {
$_SESSION['error'] = 'Please provide Username and Password';
header('Location:index.php');
}
Try THis!
U need to add $stmt->bind_result(); after $stmt->execute();
$dbh = new mysqli($host, $username, $password, $database);// in connections.php
<?php
include('connections.php');
include('config.php');
include('comman_functions.php');
if(isset($_POST['password']) && $_POST['password']!='' && isset($_POST['username']) && $_POST['username']!='' && isset($_POST['location']) && $_POST['location']!=''){
$username = "DemoUser";
$stmt = $dbh->prepare("SELECT * FROM users WHERE UserName =? ");
$stmt->bind_param("s", $username);
$stmt->execute();
$stmt->bind_result();
error_log($stmt->num_rows);
if($stmt->num_rows>0){
$row = $stmt->fetch();
error_log("logged in!!!");
$stmt->close();
}else{
$_SESSION['error'] = 'Invalid Username or Password';
header('Location:index.php');
}
}else{
$_SESSION['error'] = 'Please provide Username and Password';
header('Location:index.php');
}
?>
If you have problems making work this num_rows, you have to declare ->store_result() first.
<?php
$mysqli = new mysqli("localhost","root", "", "tables");
$query = $mysqli->prepare("SELECT * FROM table1");
$query->execute();
$query->store_result();
$rows = $query->num_rows;
echo $rows;
i have a php login script which is accessed with a simple form:
<?php
session_start();
try{
$user = 'root';
$pass = null;
$pdo = new PDO('mysql:host=localhost; dbname=divebay;', $user, $pass);
if(isset($_SESSION['loggedin'])){
echo "1"; //already logged in
}
else{
$username = $_POST['username'];
$password = sha1($_POST['password']);
$ucheck = $pdo->prepare('SELECT * FROM user WHERE username = ?');
$ucheck->bindValue(1, $username);
$ucheck->execute();
if($ucheck->fetch(PDO::FETCH_OBJ)){
$stmt = $pdo->prepare('SELECT * FROM user WHERE username = ? AND password = ?');
$stmt->bindValue(1, $username);
$stmt->bindValue(2, $password);
if($stmt->fetch(PDO::FETCH_OBJ)){
$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['username'] = $row['username'];
$_SESSION['loggedin'] = 'YES';
$_SESSION['location'] = $row['location'];
echo "2"; //logged in
}
else{
echo "3"; //password incorrect
}
}
else{
echo "4"; //user does not exist
}
}
}catch(PDOException $e){
echo $e->getMessage();
}
?>
but when i attempt to run it using an account that i just created and have confirmed to exist within the database, i get no response from this script. i would expect it to echo 2 given that the login information is correct, but i get nothing
can anyone suggest what ive done wrong here?
It looks like you forgot to execute() the statement:
if($ucheck->fetch(PDO::FETCH_OBJ)){
$stmt = $pdo->prepare('SELECT * FROM user WHERE username = ? AND password = ?');
$stmt->bindValue(1, $username);
$stmt->bindValue(2, $password);
// Execute it!!!
if ($stmt->execute()) {
$row = $stmt->fetch(PDO::FETCH_OBJ);
if ($row) {
// And don't call fetch() again, since you would already have advanced
// the record pointer in the first fetch() above. If one record was returned,
// this one would always be FALSE.
//$row = $stmt->fetch(PDO::FETCH_ASSOC);
$_SESSION['username'] = $row['username'];
$_SESSION['loggedin'] = 'YES';
$_SESSION['location'] = $row['location'];
echo "2"; //logged in
}
// else execute failed...
}
are you sure session.use_cookies = 1 in php.ini?
please make sure have name is PHPSESSION cookie.