如何防止显示PDO错误? [英] How to prevent showing PDO error?
问题描述
当PDO execute()出现错误时,由于某种原因它会输出错误?
When there is an error from PDO execute(), for some reason it outputting the error?
我该如何防止....我想将错误存储到$ data ['error']
How do I prevent that.... I would like to store an error into $data['error']
if (!$query->execute()) {
$data['success'] = 'false';
echo json_encode($data);
return;
}
从控制台日志中:
<br />
<b>Warning</b>: PDOStatement::execute() [<a href='pdostatement.execute'>pdostatement.execute</a>]: SQLSTATE[HY093]: Invalid parameter number: number of bound variables does not match number of tokens in <b>C:\wamp\www\site\application\controller\ContactController.php</b> on line <b>101</b><br />
{"success":"false"}
推荐答案
要结合其他两个提示,首先将PDO设置为使用异常而不是php错误:
To combine what the two other anwsers say, first set PDO to use exceptions instead of php errors :
$db->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
然后使用try ... catch块来处理任何错误.
Then use a try... catch block to handle any error.
$db->beginTransaction();
try{
/* Do your database things here */
}
catch(Exception $e){
$db->rollBack();
return;
}
$db->commit();
return;
您还可以设置自己的php错误处理程序,该错误处理程序可用于将所有错误记录在文件中而不显示任何内容. 请参阅php文档: http://php.net/manual/zh/function.set-error-handler.php
You could also setup your own php error handler which could be used to log all errors in a file and not display anything. See the php documentation : http://php.net/manual/en/function.set-error-handler.php
这篇关于如何防止显示PDO错误?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!