Question

Making the switch to PDO from MySQL in PHP. In the past, when a query was ran and wasn't executed for whatever reason, I was able to send myself an email with the mysql_error() message in the body like so:

$query = "SELECT dogs FROM animals";
$res = mysql_query($query);

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

From that I would be alerted by an emil when something was wrong with the database on a website.

My PDO setup is as follows:

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

I have a try catch in the PDO connection itself but I would like to get error messages for prepare and execute as they happen like so:

$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 an email subject? I'm able to get a logical error message if a prepare fails be using errorInfo() but on execute errors(such as invalid parameter counts for arrays), I can't seem to get an error message.

Thanks for any and all help.

Was it helpful?

Solution

Use try/catch

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

OTHER TIPS

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);
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top