Share on Google+Share on Google+

PDO Error Handling

Advertisement
In this tutorial we will study about PDO Error Handling Technique in PHP, how to access MySQL using PDO Error Handling Technique, How to retrieve data etc. Examples will make this clearer.

PDO Error Handling:

In this current tutorial we will study about the error handling methodology in PDO extension. In general we use try and catch block to handle the errors in the database connection but to handle other kind of errors and warnings could be handled as well in this extension. Following example illustrates this concept:

Example:

<?php

$host='localhost';

$user='root';

$pass='';

$db='DB';

try{

$dbh=new PDO("mysql:$host;dbname=$db",$user,$pass);

$sql = "SELECT username FROM emp_details";

$result=$dbh->exec($sql);

foreach ($dbh->query($sql) as $row)

{

print $row['emp_first_name'] .' - '. $row['emp_last_name'] . '<br />';

}

$dbh = null;

}

catch(PDOException $e)

{

echo $e->getMessage();

}

?>

Output:

Warning: Invalid argument supplied for foreach() in C:\xampp\htdocs\PHP-AJAX\pdo.php on line 10

Advertisements

Posted on: April 6, 2010 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Share this Tutorial Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.