如何检索 PDO 结果==false?

发布于 2024-10-12 22:52:09 字数 424 浏览 1 评论 0原文

我正在将 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 />';
  }
}

I'm converting my mysql_query() calls to PDO but don't understand how to get a false result on failure. This is my code:

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

This is what I'm trying to do but does not work:

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

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

套路撩心 2024-10-19 22:52:09

使用 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非常仔细地研究示例。

When using PDO the nature of querying usually goes down like so:

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();
}

you should read errorInfo very carefully and study the examples.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文