2
votes

How can I recognize a fetch error or empty result from a execute error with php PDO mysql driver?

  $sql = ' SELECT * ';
  $sql .= ' FROM test ';
  $sql .= ' WHERE id = 432 ';

  $statement = $this->_db->prepare($sql);
  $status = $statement->execute();

  var_dump($status);

  $result = $statement->fetch(\PDO::FETCH_ASSOC);

  var_dump($result);

  output:
  bool(true)
  bool(false)

So, I prepare statement with pdo, then execute sql, and status is true because there aren't error. Then I fetch result, and in this specific case a row with id = 432 isn't exist. So fetch method return false. My problem is that fetch method return false also when there is a error!.

How can I sure that fetch "false" result is a error or empty result?

1

1 Answers

0
votes

If there's an error then PDO will throw an exception which you can catch. Wrap your code with a try catch and that should catch any exceptions.

try {
    $rs = $db->prepare('SELECT * FROM foo');
    $rs->execute();
    $foo = $rs->fetchAll();
} catch (Exception $e) {
    echo 'Error: '.$e->getMessage();
}