I’m trying to set up a login system and am having trouble with checking the number of rows returned from my PDO call to my database. The following code should return 0 rows when a bad username and/or password is supplied, but it seems to be returning 1 row regardless of the password or username.
require_once("includes/database.php");
session_start();
$dbh = db_connect();
$response = array();
$user = $_POST['username'];
$password = $_POST['password'];
$check_login = "SELECT * FROM user WHERE user=:user AND password=:password LIMIT 1";
$check_login_stmt = $dbh->prepare($check_login);
$check_login_stmt->bindParam(":user", $user);
$check_login_stmt->bindParam(":password", $password);
if(!$check_login_stmt->execute()) {
$response['code'] = "failure";
$response['err'] = $check_login_stmt->errorInfo();
$response['reason'] = "bad_query";
} else {
if(count($user = $check_login_stmt->fetch()) > 0) {
$_SESSION['login'] = true;
$_SESSION['pb_committee'] = $user['pb_committee'];
$response['code'] = "success";
$response['count'] = count($user);
} else {
$response['code'] = "failure";
$response['reason'] = "bad_reqs";
}
}
echo json_encode($response);
When I do a count($user = $check_login_stmt->fetchAll()) > 0 it works. But I don’t understand why and I’d rather use fetch() because I’m limiting it to one row in the SELECT statement.
Any suggestions are much appreciated.
Anything passed to
count()that isn’t already an array is cast to an array. For most things, this will result incount()returning1(NULLbeing the only exception I can think of right now).That said, you should check
PDO‘s fetch mode, as you might be getting back a non-array, which would be causing the described behavior.