问题
When there is an error from PDO execute(), for some reason it outputting the 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;
}
From Console Log:
<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"}
回答1:
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);
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;
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
回答2:
You can change the error mode to your liking, e.g.:
$conn = new PDO(...);
$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
Please find further reference at http://uk.php.net/manual/en/pdo.error-handling.php
回答3:
Use PHP's try catch
try{
doPDO();
}
catch (PDOException $err) {
echo "pdo failed";
}
来源:https://stackoverflow.com/questions/5817705/how-to-prevent-showing-pdo-error