How to handle errors from PDO fetch () correctly?

The error handling document for fetch () seems obscure, and I did not find the answer anywhere after a lot of searching. The general usage model for extraction, as shown in the document, is:

while ( $row = $stmt->fetch() ) { // do something with $row } 

The PHP document at http://www.php.net/manual/en/pdostatement.fetch.php says:

In all cases, FALSE is returned on error.

What does denial mean? Error? Failed to get more rows? My question is: when fetch () returns FALSE, what is the best way to detect errors? It seems like after the loop I need to distinguish between the error case and the “more lines” case.

Should I call $ stmt-> errorCode () and see if it has '00000'?

+4
source share
2 answers

fetch () will return false when no more data is selected. There may also be another case where a crash does occur, for example. mysql is dead or the connection was lost while executing a fetch cycle. But generally speaking, such a “real” failure is quite rare, and you most often get a “lie because there is no more data”.

If you're really paranoid about writing error handling, then by all means, put the sql error code code after the while loop to catch cases where something really exploded.

+3
source

To handle query errors (sql errors do not occur during extraction) and a more general PDO error, you should try using PDO::ERRMODE_EXCEPTION . Additionally, the PdoStatement returned by query() implements Traversable, so you can skip using fetch() for a simple query:

 try { $db = new PDO('sqlite:mydb.db'); $db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); // Set Errorhandling to Exception foreach($db->query("SELECT...") as $row) { //Do domething } $db = null; // "Disconnect" } catch (PDOException $err) { //Handling query/error } 

The call will be called if the request encounters an error (not fetch ()).

Fetch will always return false when it reaches the end of your result set.

+4
source

All Articles