PDO 错误消息?

2022-08-30 11:47:40

这是我的代码片段:

$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());

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

数组 ( [0] = > 00000 )

如何获得更好的错误描述,以便调试问题?


答案 1

请尝试以下操作:

print_r($sth->errorInfo());

在准备之前添加以下内容:

$this->pdo->setAttribute( PDO::ATTR_ERRMODE, PDO::ERRMODE_WARNING );

这将更改 PDO 错误报告类型,并导致它在出现 PDO 错误时发出警告。它应该可以帮助您跟踪它,尽管您的错误信息应该设置了赌注。


答案 2

老线程,但也许我的答案会帮助某人。我通过以下方式解决方法是首先执行查询,然后设置一个错误变量,然后检查该错误变量数组是否为空。请参阅简化示例:

$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.
}

推荐