2

I have code:

$stmt = $db->prepare(" bla bla ");
$stmt->execute();
print_r($db->errorInfo());

This returns: Array ( [0] => 00000 [1] => [2] => )

Why not returned error info ?

Oto Shavadze
  • 40,603
  • 55
  • 152
  • 236
  • 4
    Have you tried `print_r($stmt->errorInfo());`? – andrewsi Jul 09 '13 at 15:00
  • I don't know why it doesn't but Exceptions are better anyway. [PDO query fails but I can't see any errors. How to get an error message from PDO?](http://stackoverflow.com/a/15990858/285587) – Your Common Sense Jul 09 '13 at 15:15

2 Answers2

6

The following reports the error correctly:

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);

if (($stmt = $dbh->prepare(" bla bla ")) === false) {
    print_r($dbh->errorInfo());
}

if ($stmt->execute() === false) {
    print_r($stmt->errorInfo());
}

Note in the above that parse errors caused during prepare() are reported against $dbh. Whereas even if the prepare() succeeds, then execute() may cause an error, but that error is reported against $stmt.

In the test above, I got the error report immediately after the prepare():

Array
(
    [0] => 42000
    [1] => 1064
    [2] => You have an error in your SQL syntax; 
           check the manual that corresponds to your MySQL server version for the right 
           syntax to use near 'bla bla' at line 1
)

But this behavior changes if you use emulated prepares.

When you enable that attribute, the prepare() is virtually a no-op. It just saves the query string in the $stmt, and then the actual prepare of the statement is delayed until you call execute(). So the error, if any, is reported against $stmt whether it happens at prepare time or at execute time.

I tested changing the error-reporting line as follows:

$dbh->setAttribute(PDO::ATTR_EMULATE_PREPARES, true);

// prepare won't report SQL errors, it's virtually a no-op.
if (($stmt = $dbh->prepare(" bla bla ")) === false) {
    print_r($dbh->errorInfo());
}

// execute will report errors of parsing or execution.
if ($stmt->execute() === false) {
    print_r($stmt->errorInfo());
}

In this case, no error was reported at prepare(), and but I got the same error as above at execute(). Again, you must examine $stmt to get the error after execute().

Bill Karwin
  • 538,548
  • 86
  • 673
  • 828
-2

SQLSTATE 00000 means "Success". Per the PHP documentation:

If the SQLSTATE error code is not set or there is no driver-specific error, the elements following element 0 will be set to NULL.

TML
  • 12,813
  • 3
  • 38
  • 45