bart
bart

Reputation: 15288

How to retrieve PDO result==false?

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 />';
  }
}

Upvotes: 1

Views: 298

Answers (1)

RobertPitt
RobertPitt

Reputation: 57268

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.

Upvotes: 2

Related Questions