82
    $st = $db->prepare("SELECT * FROM c6ode");

How can I check the intentional mysql error for the query in above case?

Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
TPSstar
  • 881
  • 1
  • 8
  • 13

5 Answers5

79

You need to set the error mode attribute PDO::ATTR_ERRMODE to PDO::ERRMODE_EXCEPTION.

And since you expect the exception to be thrown by the prepare() method, you should disable the PDO::ATTR_EMULATE_PREPARES feature. Otherwise the MySQL server doesn't "see" the statement until it's executed.

<?php
$pdo = new PDO('mysql:host=localhost;dbname=test;charset=utf8', 'localonly', 'localonly');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$pdo->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$pdo->prepare('INSERT INTO DoesNotExist (x) VALUES (?)');

prints (or logs, depends on the PHP settings)

SQLSTATE[42S02]: Base table or view not found: 
1146 Table 'test.doesnotexist' doesn't exist
Your Common Sense
  • 156,878
  • 40
  • 214
  • 345
VolkerK
  • 95,432
  • 20
  • 163
  • 226
56

I'm using this without any additional settings:

if (!$st->execute()) {
    print_r($st->errorInfo());
}
The Codesee
  • 3,714
  • 5
  • 38
  • 78
ladar
  • 5,858
  • 3
  • 26
  • 38
25

I'm guessing that your complaint is that the exception is not firing. PDO is most likely configured to not throw exceptions. Enable them with this:

$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION); 
Steve Rukuts
  • 9,167
  • 3
  • 50
  • 72
  • Nope still not working, i know my query is wrong, but i want to display that error. – TPSstar Jan 08 '12 at 08:48
  • You may find that there is an error with the call to `new PDO(...` itself. Try increasing the level of error_reporting by setting for example `error_reporting(E_ALL)`. – Steve Rukuts Jan 08 '12 at 08:49
14

a quick way to see your errors whilst testing:

$error= $st->errorInfo();
echo $error[2];
Lan
  • 1,874
  • 2
  • 20
  • 37
3

/* Provoke an error -- the BONES table does not exist */

$sth = $dbh->prepare('SELECT skull FROM bones');
$sth->execute();

echo "\nPDOStatement::errorInfo():\n";
$arr = $sth->errorInfo();
print_r($arr);

output

Array
(
    [0] => 42S02
    [1] => -204
    [2] => [IBM][CLI Driver][DB2/LINUX] SQL0204N  "DANIELS.BONES" is an undefined name.  SQLSTATE=42704
)
Timothy Nwanwene
  • 995
  • 11
  • 18