I am working on a PHP PDO Login system but i keep getting an error, perhaps some part of my code is incorrect.
//LOG IN VERIFICATION
if (isset($_POST['username'],$_POST['pass'])) {
try {
$con = new PDO("mysql:host=" . host . ";dbname=" . database, user, auth);
$con->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$con->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
if (!empty($_POST['username'])&& !empty($_POST['pass'])) {
//username and password sent from Form
$usernames = trim($_POST['username']);
$password = $_POST['pass'];
$select= $con -> prepare("SELECT username,password FROM users WHERE username='$username' AND password='$password'");
$select ->execute();
$results = $select->fetch(PDO::FETCH_ASSOC);
if (count($results) > 0 && password_verify($password, $results['password'])) {
header('location:home.php');
} else{
header('location:login.php');
}
}
} catch(PDOException $e) {
echo 'ERROR: ' . $e->getMessage();
}
}
I suspect the error to be here
$select= $con -> prepare("SELECT username,password FROM users WHERE username='$username' AND password='$password'");
$select ->execute();
$results = $select->fetch(PDO::FETCH_ASSOC);
because i verified the connection to the database. Any help will be appreciated.
You're assigning to $usernames
, not $username
. However, the real problem is count($results)
- you cannot count the rows this way. Which means, the count will be 0, hence the else
branch is executed. See here: Row count with PDO .
Edit: In such cases, simply debug your code and var_dump(count($results))
, for example. You have a simple if
statement - if an unexpected branch is executed, something is wrong with the if
condition.
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.