PDO Error Handling


 

PDO Error Handling

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.

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

Ads