2

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?

paganotti
  • 5,591
  • 8
  • 37
  • 49

1 Answers1

1

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();
}
aziz punjani
  • 25,586
  • 9
  • 47
  • 56
  • 5
    That requires PDO::ATTR_ERRMODE to be set accordingly: http://us.php.net/manual/en/pdo.setattribute.php – DCoder Apr 13 '12 at 19:13
  • This works fine with pdo_mysql but let me add a quick note for pdo_sqlsrv: in my experience, it throws an exception even when the recordset is empty. – Eugenio Oct 30 '18 at 11:03
  • Precisely, the error is "There are no more rows in the active result set" and it is produced when you try to fetch a recordset which is already completely fetched. This not happens with pdo_mysql, which just returns false. – Eugenio Oct 30 '18 at 11:23
  • More details here https://stackoverflow.com/questions/53063059/pdo-sqlsrv-how-to-recognize-if-fetch-false-is-an-error-or-empty-recordset , it seems that you get the error only starting from the SECOND TIME you try to fetch an empty recordset – Eugenio Oct 31 '18 at 21:28