Search code examples
phpmysqlipdoresultset

Why is PDO returning Result when it shouldn't?


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 echoes 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 last DELETE, INSERT, or UPDATE statement executed by the corresponding PDOStatement object.
If the last SQL statement executed by the associated PDOStatement was a SELECT.
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.


Solution

  • Do you maybe mean if (count($stmt->fetchAll()) > 0) {