I am working on a login form script I obtained from a tutorial from https://codeshack.io/secure-login-system-php-mysql/. I have followed all steps, but every single time I click login, I get the innermost else statement error of "Incorrect username and/or password!". I have verified that I am connected to the DB correctly. I only have one row in my table as I'm only in testing stages at the moment, and I have verified that I'm typing the password correctly. Here is the code:
$con = mysqli_connect($DB_HOST, $DB_USER, $DB_PASS, $DB_NAME);
if ( mysqli_connect_errno() ) {
// If there is an error with the connection, stop the script and display the error.
die ('Failed to connect to MySQL: ' . mysqli_connect_error());
}
// Now we check if the data was submitted, isset will check if the data exists.
if ( !isset($_POST['username'], $_POST['password']) ) {
// Could not get the data that should have been sent.
die ('Username and/or password does not exist!');
}
// Prepare our SQL
if ($stmt = $con->prepare('SELECT id, password FROM users WHERE username = ?')) {
// Bind parameters (s = string, i = int, b = blob, etc), hash the password using the PHP password_hash function.
$stmt->bind_param('s', $_POST['username']);
$stmt->execute();
$stmt->store_result();
// Store the result so we can check if the account exists in the database.
if ($stmt->num_rows > 0) {
$stmt->bind_result($id, $password);
$stmt->fetch();
// Account exists, now we verify the password.
if (password_verify($_POST['password'], $password)) {
// Verification success! User has loggedin!
$_SESSION['loggedin'] = TRUE;
$_SESSION['name'] = $_POST['username'];
$_SESSION['id'] = $id;
echo 'Welcome ' . $_SESSION['name'] . '!';
} else {
echo 'Incorrect username and/or password!';
}
} else {
echo 'Incorrect username and/or password!';
}
$stmt->close();
} else {
echo 'Could not prepare statement!';
}
if (password_verify) is where I'm hitting the else statement when I want to be entering the if statement for a successful login. I am a little leery of "selecting id,password from the db where username = ?" because shouldn't "username = ?" be equal to what the user has entered into the input field that is named username instead of "?"? (new to PHP and MySQL - maybe I'm completely wrong in this thinking!)
Does anybody have any idea what's happening? I really appreciate the help!
P.S. I am absolutely sure the password verify else is the error message I'm receiving as on my end, I changed the echo statement from the one below it to avoid confusion.