确定哪个预准备语句在try / catch中导致错误

时间:2014-07-03 18:09:58

标签: php oop pdo try-catch

在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
}

3 个答案:

答案 0 :(得分:1)

要确定哪个查询失败,请在不同的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
}

答案 1 :(得分:0)

您可以查看每个语句的error code。 (阅读有关数据库代码的文档)。 null表示该语句未执行。

答案 2 :(得分:0)

如果你要捕获PDOException,你可以在try catch中包含prepare(),如果可能的话,你还应该使用一个查询来插入。

准备在失败时返回false,因此检查$ p的值并抛出异常