在catch子句中,我如何确定哪个准备好的语句导致了错误,以便我可以对其应用debugDumpParams ?请看下面的例子。
$p1=db::db()->prepare("INSERT INTO t1 (a,b,c) VALUES (:a,:b,:c)");
$p2=db::db()->prepare("INSERT INTO t2 (a,b,c) VALUES (:a,:b,:c)");
try{
$data=array('a'=>1,'b'=>2,'c'=>3);
$p1->execute($data);
$p2->execute($data);
}
catch(PDOException $e){
//Display debugDumpParams() for the statement that caused the error
}
要确定哪个查询失败,请在不同的try catch块中执行它们。
$data=array('a'=>1,'b'=>2,'c'=>3);
$p1 = db::db()->prepare("INSERT INTO t1 (a,b,c) VALUES (:a,:b,:c)");
try {
$p1->execute($data);
} catch(PDOException $e) {
// Display debugDumpParams() for the statement that caused the error
// First query has failed
}
$p2 = db::db()->prepare("INSERT INTO t2 (a,b,c) VALUES (:a,:b,:c)");
try {
$p2->execute($data);
} catch(PDOException $e) {
// Display debugDumpParams() for the statement that caused the error
// Second query has failed
}
您可以检查每个语句的错误代码。(阅读有关数据库代码的文档)。
如果要捕获PDOException,不妨在try捕获中包含prepare(),如果可能的话,还应该使用一个查询来插入。
Prepare失败时返回false,因此检查$p的值并抛出异常