如何将一些 mysql 转换为 pdo

how to convert some mysql into pdo

谁能帮我把它转换成 PDO

// verify email and password pair
$userid = 0;
$query = sprintf("SELECT id FROM users WHERE LOWER(email)='%s' AND passwordhash='%s'",strtolower($email),$pwdhash);
$resource = mysql_query($query);
if ($resource)
{
    $row = mysql_fetch_row($resource);
    if (isset($row[0]))
        $userid = $row[0];
}

这是我的尝试:

$userid = 0;
$resource = $dbh->query("SELECT id FROM users WHERE LOWER(email)=':email' AND passwordhash=':hash'");
$resource->bindValue(':email',$email,PDO::PARAM_STR);
$resource->bindValue(':hash',$pwdhash,PDO::PARAM_STR);
if ($resource->execute())
{
    $result = array();
    while ($row = $resource->fetch()) {
        array_push($result, $row);
    }

    if (isset($result[0]))
    $userid = $result[0];

    $dbh = null;
    return $result;
}   

我很确定 if 语句中的部分有问题

其他尝试:

    $userid = 0;
    $resource = $dbh->query("SELECT id FROM users WHERE LOWER(email)=':email' AND passwordhash=':hash'");
    $resource->bindValue(':email',$email,PDO::PARAM_STR);
    $resource->bindValue(':hash',$pwdhash,PDO::PARAM_STR);
    if ($resource)
    {
        $row = $resource->fetchAll();
            if (isset($row[0]))
            $userid = $row[0];
    }

    // close database and return 
    $dbh = null;
    return $userid;
}

尝试了几次...

试试这个,

使用 prepare 而不是 query,准备的结果是一个语句句柄,可用于将值绑定到您在准备中使用的命名参数。

$userid = 0;
$stmt = $dbh->prepare("SELECT id FROM users WHERE LOWER(email)=:email AND passwordhash=:hash");
$stmt->bindValue(':email',$email,PDO::PARAM_STR);
$stmt->bindValue(':hash',$pwdhash,PDO::PARAM_STR);
if ($stmt->execute())
{
    $result = array();
    while ($row = $stmt->fetch()) {
        array_push($result, $row);
    }

    if (isset($result[0]))
    $userid = $result[0];

    $dbh = null;
    return $result;
}