I am rebuilding login page now.
I have original one without password_verify code is working fine.
Original code without password_verify code:
$username = $_POST['username'];
$password = md5($_POST['password']);
if($username != "" && $password != "") {
try {
$query = "SELECT * FROM `admin` WHERE `u_name`=:username and `u_pass`=:pass";
$stmt = $db->prepare($query);
$stmt->bindParam('username', $username, PDO::PARAM_STR);
$stmt->bindValue('pass', $password, PDO::PARAM_STR);
$stmt->execute();
$count = $stmt->rowCount();
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if($count == 1 && !empty($row)) {
$_SESSION['sess_user_id'] = $row['aID'];
$_SESSION['sess_username'] = $row['u_name'];
echo "home.php";
} else {
echo "invalid";
}
} catch (PDOException $e) {
echo "Error : ".$e->getMessage();
}
} else {
echo "Both fields are required!";
}
But I edited and added password_verify code below to original one and it won't work.
$username = $_POST['username'];
$password = $_POST["password"];
if($username != "" && $password != "") {
try {
$stmt = $db->prepare("SELECT * FROM admin WHERE u_name = :uname" );
$stmt->execute(array(':uname' => $_POST['username']));
$row = $stmt->fetchAll(PDO::FETCH_ASSOC);
if(count($row)>0) {
if (password_verify($password, $row['u_pass'])) {
$_SESSION['sess_user_id'] = $row['aID'];
$_SESSION['sess_username'] = $row['u_name'];
echo "home.php";
} else {
echo "invalid";
}
} catch (PDOException $e) {
echo "Error : ".$e->getMessage();
}
} else {
echo "Both fields are required!";
}
}
I'm still beginner for PDO password_veryfy I can't figure it out ....
Would you please tell me what is wrong / where to fix it?
I appreciated your help.
Thank you for your time.
The problem is that when you fetch $row
in the new version with fetchAll()
, it is an array of records, the row your after is the first record in the result. So you need to check the first row in the result...
if(count($row)>0) {
if (password_verify($password, $row[0]['u_pass'])) {
$_SESSION['sess_user_id'] = $row[0]['aID'];
$_SESSION['sess_username'] = $row[0]['u_name'];
echo "home.php";
} else {
echo "invalid";
}
In the previous version you used fetch()
which is the main difference here.
fetchAll()
returns a 2-dimensional array. Since there can only be one row in the table for a user, just use fetch()
like you did in your original code.
$row = $stmt->fetch(PDO::FETCH_ASSOC);
if ($row && password_verify($password, $row['u_pass'])) {
$_SESSION['sess_user_id'] = $row['aID'];
$_SESSION['sess_username'] = $row['u_name'];
echo "home.php";
} else {
echo "invalid";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.