PDO查询无效

时间:2012-07-23 14:08:54

标签: php pdo

我不能为我的生活弄清楚为什么这不起作用。我有一个不同的网站区域使用几乎完全相同的代码,它工作得很好。我确定这是显而易见的,但我对这些东西很陌生。没有任何错误或任何错误;它什么也没做。 $ name变量工作正常(我已经测试过),数据库是最新的。

try {
     $db = new PDO($dbhost, $dbuser, $dbpassword);
     $statement = $db->prepare("select first, last from users where email = $name");
     $result = $statement->fetch();
     $first = $result[first];
     $last = $result[last];
}catch(PDOException $e) {
     echo $e->getMessage();
}

2 个答案:

答案 0 :(得分:1)

你必须使用execute()

try {
$db = new PDO($dbhost, $dbuser, $dbpassword);
$statement = $db->prepare("select first, last from users where email = ?");
$statement->execute(array($name));
$result = $statement->fetch();
$first = $result[first];
$last = $result[last];}

catch(PDOException $e) {echo $e->getMessage();}

答案 1 :(得分:0)

在实际执行查询之前,无法获取行;你只准备了查询。最终的问题是你没有打电话给$statement->execute()。正确的PDO习语是这样的:

$statement = $db->prepare("select first, last from users where email = ?");
if (!$statement->execute(array($name))) {
    // Handle error
}
$result = $statement->fetch();
$statement->closeCursor();

完成提取行后,请不要忘记closeCursor()调用。在某些不支持同一客户端并发查询的数据库系统上,不调用此函数可能导致下一个查询无法执行。