PDO: Error Handling

PHP Data Objects (PDO) Step By Step Tutorial - Part 6: When everything is okey, we didn't need error checking. But, we never know (especially at real world) what will happen, error handling is needed. We should check for errors when opening the connection to database, select database, and run query.

We can implement error handling at PDO like this:

// configuration
$dbtype		= "sqlite";
$dbhost 	= "localhost";
$dbname		= "test";
$dbuser		= "root";
$dbpass		= "admin";

  // database connection
  $conn = new PDO("mysql:host=$dbhost;dbname=$dbname",$dbuser,$dbpass);
catch(PDOException $pe)
  die('Connection error, because: ' .$pe->getMessage());

// query
$sql = "SELECT title FROM books ORDER BY title";
$q	 = $conn->query($sql);

  die("Execute query error, because: ". $conn->errorInfo());


// fetch
while($r = $q->fetch()){


Previous: PDO: Posibble Fetch Mode
Next: PDO: Prepared Statement

Series this article:
PDO: Introduction PHP Data Object
PDO: Activation PHP Data Objects Extension
PDO: Connecting Use PHP Data Object
PDO: Portable Connection to Database
PDO: Posibble Fetch Mode
PDO: Error Handling
PDO: Prepared Statement
PDO: Positional and Named Placeholders
PDO: Insert and Update Statement Use Prepared Statement
PDO: Prepared Statement and Bound Values
PDO: Working With BLOBs
PDO: Alternative Retrieve BLOB Data
PDO: Setting Connection Attributes
PDO: Error Mode Attributes
PDO: Improve Performance with Persistent Connection
PDO: Getting Connection Attributes

Bookmark and Share Tag: Category: PHP Database Post : April 19th 2008 Read: 165,176


blog comments powered by Disqus