Synyster Synyster - 4 months ago 19
SQL Question

Getting hashed password with prepared statements

I can't get this to work. I am new to working with prepared statements so i i'm kinda 50/50 on what i'm doing.

Upon registration, the password is hashed with


Now, i'm trying to get my login page to function with this but i dont know where / how to write it with the

$username = $_POST['username'];
$password = $_POST['password'];

$sql = "SELECT * FROM users WHERE BINARY username=? AND password=?";
$stmt = $db->prepare($sql);
$result = $stmt->get_result();
$num_rows = $result->num_rows;

if($num_rows == 1){

$rows = $result->fetch_assoc();
if(password_verify($password, $rows['password'])){
$_SESSION['loggedin'] = $username;
$_SESSION['country'] = $rows['country'];
$_SESSION['email'] = $rows['email'];
$_SESSION['avatar'] = $rows['u_avatar'];
$_SESSION['is_gm'] = $rows['is_gm'];
$_SESSION['user_lvl'] = $rows['user_lvl'];
$_SESSION['totalposts'] = $rows['post_total'];
$_SESSION['totalcoins'] = $rows['coins_total'];
$_SESSION['totalvotes'] = $rows['vote_total'];
$_SESSION['secquest'] = $rows['sec_quest'];
$_SESSION['secanswer'] = $rows['sec_answer'];
$_SESSION['join_date'] = $rows['join_date'];

header("Location: /index.php");
} else {
echo "<p class='error_msg'>No accounts could be found with the given credentials.</p>";


I would assume that the password verify would before
if($num_rows == 1)
but as i said, i have no idea.


Your query is essentially:

SELECT * FROM users WHERE username=username AND password_hash=plain_text_password

This isn't going to work. If you're relying on PHP password hashing, you can't do a password comparison on the SQL level. Retrieve the password hash from the database then do the password_verify (exclude the password=?) in your WHERE arguments.