简体   繁体   English

PHP MYSQL if陈述PDO结果

[英]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. 如果确实如此,则仅返回true。 If it doesn't, then it returns false. 如果不是,则返回false。

Anyway, regardless of the user and password existing in the database, for some reason it will not evaluate to true! 无论如何,无论数据库中存在用户名和密码,由于某种原因,它都不会等于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. 由于某些未知原因,您正在传递"USE $dbname"字符串来执行。
remove that string. 删除该字符串。

Also, you are trying to catch an exception but apparently don't tell PDO to throw them. 另外,您正在尝试捕获异常,但显然不要告诉PDO抛出异常。 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). 如果您的问题不同,则必须询问(或更好-Google针对这个问题)。
Refer to PDO tag wiki for the proper connect options including database selection and error reporting. 有关正确的连接选项(包括数据库选择和错误报告),请参考PDO标签Wiki

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. 这是本地服务器示例,只需将yourDbName更改为您的数据库名称。 I just run this code on my local server and it is working. 我只是在本地服务器上运行此代码,它正在工作。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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