简体   繁体   中英

PHP MYSQL if statement on PDO result

Have a look through the code below. This is supposed to check whether or not a database contains a given user. If the it does, it just returns true. If it doesn't, then it returns false.

Anyway, regardless of the user and password existing in the database, for some reason it will not evaluate to true! ! !

function databaseContainsUser($email, $password)
{

    include $_SERVER['DOCUMENT_ROOT'].'/includes/db.inc.php';

    try
    {
        $sql = 'SELECT COUNT(*) FROM wl_user
                WHERE email = :email AND password = :password'; 
        $s = $pdo->prepare($sql);
        $s->bindValue(':email', $email);
        $s->bindValue(':password', $password);
        $s->execute("USE $dbname");
    }
    catch (PDOException $e)
    {
        $error = 'Error searching for user. ' . $e->getMessage();
        include $_SERVER['DOCUMENT_ROOT'].'/includes/error.html.php';
        exit();
    }

    $row = $s->fetch(PDO::FETCH_NUM);

    if ($row[0] > 0)
    {   
        return TRUE;
    }
    else
    {
        return FALSE;
    }
}

Any help would be appreciated

For some unknown reason you are passing "USE $dbname" string to execute.
remove that string.

Also, you are trying to catch an exception but apparently don't tell PDO to throw them. And you are catching it only to echo a message, which is a big no-no. I've explained the right way recently in this answer

If your problem is different, you have to ask (or better - google for this very problem).
Refer to PDO tag wiki for the proper connect options including database selection and error reporting.

Try this

 try
{
    $pdo = new PDO('mysql:host=localhost;dbname=yourDbName;', 'root', '',
    array(PDO::ATTR_PERSISTENT => true));
    $sql = 'SELECT count(*) FROM user WHERE email = :email AND password = :password'; 
    $s = $pdo->prepare($sql);
    $s->bindValue(':email', $email);
    $s->bindValue(':password', $password);
    $s->execute();
}

This is local server example, just change yourDbName to your db name. I just run this code on my local server and it is working.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM