Reputation: 7257
I have just one text field where a user can enter there username or email address to reset there password.
First here is the code: (I only included code that I know where problem resides).
try {
// connect to database
$dbh = sql_con();
// prepare query
$stmt = $dbh->prepare("
SELECT COUNT(*)
FROM
users
WHERE
user_login = :username
OR
user_email = :email
");
// execute query
$stmt->execute(array(':username' => $username_email, ':email' => $username_email));
if ($stmt->fetchAll() > 0) {
// something was found
// just echoing at the moment until i figure out what i am doing wrong
echo 'i found something';
exit;
} else {
// nothing found
echo 'i found nothing';
exit;
}
}
catch (PDOException $e) {
ExceptionErrorHandler($e);
require_once($footer_inc);
exit;
}
Not sure what I am doing wrong, probably something very silly, but when I enter a username or email address that I know is not in the database it still echo
es out I found something.
What I am doing wrong?
I was going to use rowCount
but as suggested by the PHP manual it states:
PDOStatement::rowCount()
returns the number of rows affected by the lastDELETE
,INSERT
, orUPDATE
statement executed by the corresponding PDOStatement object.
If the last SQL statement executed by the associatedPDOStatement
was aSELECT
.
statement, some databases may return the number of rows returned by that statement.
However, this behaviour is not guaranteed for all databases and should not be relied on for portable applications.
So basically the PHP manual is saying I should do a Count(*)
before performing my real query then work with the result.
Upvotes: 0
Views: 248
Reputation: 31730
$statement -> fetchAll () will return an array. Comparing it to 0 makes no sense. You probably meant to count() the number of elements in the resultset returned from $statement -> fetchAll ()
Upvotes: 0
Reputation: 360662
That's because fetchAll()
returns an array. even if the query result has no rows, you still get at least an empty array, and...
php > var_dump(array() > 0);
bool(true)
You need to do
if ($stmt->rowCount > 0) { ... }
instead. And besides, you're doing a COUNT(*)
, so regardless of what's matched, you'll get a single row result that contains the matched count. You'd need to fetch that one row, and check the value of that counted field.
Upvotes: 3