【问题标题】:Determine which prepared statement causes an error in a try/catch确定哪个准备好的语句导致 try/catch 中的错误
【发布时间】:2014-07-03 18:09:57
【问题描述】:

在 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
  • @cmorrissey。不理想,因为我想要所有查询的通用捕获。
  • @MarkM 是的,我可以,但它肯定会添加一堆代码。不知道是否有更好的解决方案。
  • 可能有更好的方法 - 我不确定。但是如果你有一堆查询,你可以把它们放在一个循环中,prepareexecute 每个都有一个 try-catch。不会有更多代码。

标签: php oop pdo try-catch


【解决方案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
}

【讨论】:

    【解决方案2】:

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

    【讨论】:

      【解决方案3】:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2019-11-04
        • 2010-10-05
        • 1970-01-01
        • 1970-01-01
        • 2013-12-17
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多