PHP PDO Error Message as Variable for Emailing

Transition to PDO from MySQL to PHP. Previously, when the request was executed and not executed for any reason, I was able to send me an email with the message mysql_error () in the body like this:

$query = "SELECT dogs FROM animals"; $res = mysql_query($query); if (!$res) { $error = "Error Message: " . mysql_error(); mail(" my@email.com ","Database Error",$error); } 

From this I would be warned by the emir if something is wrong with the database on the website.

My PDO setup is as follows:

 setAttribute(PDO::ATTR_EMULATE_PREPARES,false); setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING); 

I have an attempt to catch in the PDO connection itself, but I would like to receive error messages for preparation and execution, as they occur like this:

 $query = "SELECT cats FROM animals"; $sql = $pdo->prepare($query); if (!$sql->execute()) { $error = "Error Message: " . (pdo error message here); mail(" my@email.com ","Database Error",$error); } 

Any ideas on how to assign PDO error messages in the subject line? I can get a logical error message if the preparation fails to use errorInfo (), but when I make errors (such as invalid parameter values ​​for arrays), I cannot get an error message.

Thanks for any help.

+4
source share
2 answers

Use try / catch

 try { $sql->execute(); } catch (PDOException $e) { $e->getMessage(); // This function returns the error message } 
+6
source

You can use:

 $query = "SELECT cats FROM animals"; $sql = $pdo->prepare($query); if (!$sql->execute()) { $arr = $sql->errorInfo(); $error = print_r($arr, true); mail(" my@email.com ","Database Error",$error); } 
0
source

All Articles