PDO错误消息?

JD *_*cks 37 php pdo

这是我的代码片段:

$qry = '
    INSERT INTO non-existant-table (id, score) 
    SELECT id, 40 
    FROM another-non-existant-table
    WHERE description LIKE "%:search_string%"
    AND available = "yes"
    ON DUPLICATE KEY UPDATE score = score + 40
';
$sth = $this->pdo->prepare($qry);
$sth->execute($data);

print_r($this->pdo->errorInfo());
Run Code Online (Sandbox Code Playgroud)

这应该给我一个错误,因为表甚至不存在.我得到的只是:

数组([0] => 00000)

如何更好地描述错误,以便我可以调试问题?

Ala*_*nse 93

试试这个:

print_r($sth->errorInfo());
Run Code Online (Sandbox Code Playgroud)

编辑:

在准备之前添加:

$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );
Run Code Online (Sandbox Code Playgroud)

这将更改PDO错误报告类型,并在出现PDO错误时使其发出警告.它应该可以帮助你追踪它,虽然你的errorInfo应该有赌注设置.

  • 谢谢,这给了我完全相同的东西,`Array ( [0] => 00000 )`。 (2认同)
  • 我试过PDO :: ATTR_ERRMODE,PDO :: ERRMODE_WARNING但它没有用,我仍然得到00000.任何人都有任何想法? (2认同)

小智 7

旧线程,但也许我的回答会对某人有所帮助。我通过首先执行查询,然后设置一个错误变量,然后检查该错误变量数组是否为空来解决。见简化示例:

$field1 = 'foo';
$field2 = 'bar';

$insert_QUERY = $db->prepare("INSERT INTO table bogus(field1, field2) VALUES (:field1, :field2)");
$insert_QUERY->bindParam(':field1', $field1);
$insert_QUERY->bindParam(':field2', $field2);

$insert_QUERY->execute();

$databaseErrors = $insert_QUERY->errorInfo();

if( !empty($databaseErrors) ){  
    $errorInfo = print_r($databaseErrors, true); # true flag returns val rather than print
    $errorLogMsg = "error info: $errorInfo"; # do what you wish with this var, write to log file etc...         

/* 
 $errorLogMsg will return something like: 
 error info:  
 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 'table bogus(field1, field2) VALUES                                                  ('bar', NULL)' at line 1
 )
*/
} else {
    # no SQL errors.
}
Run Code Online (Sandbox Code Playgroud)


Vik*_*ram 5

也许这篇文章太旧了,但它可能有助于为环顾四周的人提供建议:而不是使用:

 print_r($this->pdo->errorInfo());
Run Code Online (Sandbox Code Playgroud)

使用 PHP implode() 函数:

 echo 'Error occurred:'.implode(":",$this->pdo->errorInfo());
Run Code Online (Sandbox Code Playgroud)

这应该打印错误代码、详细的错误信息等,如果您使用某些 SQL 用户界面,通常会得到这些信息。

希望能帮助到你