简体   繁体   中英

How do I get meaningful error messages out of MySQL using PDO prepared statements?

Suppose I have the following table:

mysql> CREATE TABLE example (
    -> `id` INT(10) NOT NULL PRIMARY KEY AUTO_INCREMENT,
    -> `stuff` VARCHAR(255) NOT NULL
    -> );
Query OK, 0 rows affected (0.06 sec)

The stuff column was declared as NOT NULL . When a null value gets passed to it in a prepared statement, it naturally fails. Thus:

mysql> PREPARE test FROM "INSERT INTO example (stuff) VALUES (?)";
Query OK, 0 rows affected (0.00 sec)
Statement prepared

mysql> SET @a = NULL;
Query OK, 0 rows affected (0.00 sec)

mysql> EXECUTE test USING @a;
ERROR 1048 (23000): Column 'stuff' cannot be null

The error message Column 'stuff' cannot be null is pretty clear. But when I execute the exact same query using PDO's bound parameters, it doesn't give me that error message. Here's an example script:

<?php

$host = 'localhost';

$user = 'fakeuser';
$pass = 'fakepass';
$db_name = 'fakedb';

$dsn = "mysql:host=$host;port=3306;dbname=$db_name";

// Connect to the database.
try {
    $DB = new PDO(
        $dsn,
        $user,
        $pass,
        array(PDO::ATTR_PERSISTENT => true)
    );
} catch (PDOException $e) {
    print "Unable to connect to database.\n";
    exit;
}

// Make sure everything is handled in the UTF-8 character set.
$DB->exec('SET NAMES UTF8');

$SQL = 'INSERT INTO example (stuff) VALUES (:stuff)';

$query = $DB->prepare($SQL);

$values = array(
    ':stuff' => null,
);

$saved = $query->execute($values);

print "\$saved is:\n";
var_dump($saved);
print "\n\n";

print "Error code is:\n";
var_dump($DB->errorCode());
print "\n\n";

print "Error info is:";
var_dump($DB->errorInfo());
print "\n\n";

Which outputs the following:

$ php test.php

$saved is:
bool(false)

Error code is:
string(5) "00000"

Error info is:array(3) {
  [0]=>
  string(5) "00000"
  [1]=>
  NULL
  [2]=>
  NULL
}

None of that the debug info that makes it back to me through PHP is useful. How can I get it to give me the real error message instead of this 00000 junk?

Try $query->errorInfo() instead.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM