如何检索PDO结果== false?

时间:2011-01-17 02:40:58

标签: php mysql pdo

我正在将我的mysql_query()调用转换为PDO,但不了解如何在失败时获得 false 结果。这是我的代码:

$STH = $DBH->query("SELECT * FROM articles ORDER BY category");  
$STH->setFetchMode(PDO::FETCH_ASSOC);
$DBH->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_SILENT);

这是我正在尝试但不起作用的事情:

if($STH==false) {
  foreach($dbh->errorInfo() as $error) {
  echo $error.'<br />';
  }
}

1 个答案:

答案 0 :(得分:2)

使用PDO时,查询的性质通常会下降:

try
{
    $STH = $DBH->prepare("SELECT * FROM articles ORDER BY category"); //Notice the prepare
    $STH->setFetchMode(PDO::FETCH_ASSOC);
    //No need to silent as the errors are catched.

    if($STH === false) //Notice the explicit check with !==
    {
        //Do not run a foreach as its not multi-dimensional array
        $Error = $DBH->errorInfo();

        throw new Exception($Error[2]); //Driver Specific Error
    }
}catch(Exception $e)
{
    //An error accured of some nature, use $e->getMessage();
}

你应该仔细阅读errorInfo并研究这些例子。