4

I have run into a problem using PDO because an error was not caught.

The code is simple and works just fine, I'll just include a sample to avoid confusion:

$sql = 'INSERT INTO somedatetable (something) 
        VALUES (:something) 
        ON DUPLICATE KEY UPDATE something=:something';

$values = array(":something" => $something);

try {
    $stmt = $dbh->prepare($sql);    
    $stmt->execute($values);    
} catch (PDOException $e) {
    echo "Error: " . $e->getMessage() . "<br />\n";
}

The code works fine, however when working on a new module, I ran into a problem that no records were added or modified and no error was caught.

$stmt returned false but I did not have a clue why or how to find the error.

The solution was simple in the end, I was using a limited MySQL user that did not have write permissions to the table. These errors always displayed right away when using mysql, but using PDO I do not know how to get to them.

How do I get PHP / PDO to display or catch these kind of database errors?

hakre
  • 193,403
  • 52
  • 435
  • 836
jeroen
  • 91,079
  • 21
  • 114
  • 132

1 Answers1

11

PDO::errorInfo() or PDOStatement->errorInfo()

As for exceptions, check the docs for "Errors and error handling" in PDO. Exceptions aren't thrown by default, which is why you might want to enable them.

See as well:

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
Ryann Graham
  • 8,079
  • 2
  • 29
  • 32
  • 1
    Thanks, that tells me exactly what I need to know. One more question though, why is the error not caught? – jeroen Mar 27 '09 at 18:08
  • You said it returned false, that means it was caught ;-) – Ryann Graham Mar 27 '09 at 18:19
  • Ummmmmmmm, what is the point of having a catch statement then if it does not show the message? I thought the whole point of that was to get rid of these if (success) else combinations... – jeroen Mar 27 '09 at 18:31
  • Or is (PDOException $e) just wrong? I Must have caught the wrong thing but I am learning :) – jeroen Mar 27 '09 at 18:34