try / catch用于循环SQL语句

时间:2017-08-25 13:39:49

标签: php loops pdo try-catch

我试图识别try / catch失败的完整SQL语句。这是代码:

try {
    $conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    $conn->beginTransaction();

    for($counter=0;$counter<sizeof($sql);$counter++) {
        $query = $conn->prepare($sql[$counter]);
        $conn->exec($sql[$counter]);
    }
    $conn->commit();
} catch (Exception $e) {
    $err_message = "Failed while saving process....";
    log_event('submit_scores.php', $err_message);
    $err_message = "The following SQL statements were in the queue:";
    log_event('submit_scores.php', $err_message);
    for($counter=0;$counter<sizeof($sql);$counter++) {
        /* \t should be a tab character to indent the sql statements */
        $err_message = "\t" . $sql[$counter];
        log_event('submit_scores.php', $err_message);
    }

    $conn->rollBack();
    $message = "Failed: " . $e->getMessage();
    echo $message;
    $err_message = "\t" . $message;
    log_event('submit_scores.php', $err_message);
    return;
}

这会将所有SQL语句记录到日志文件中(通过log_event函数)。然后它会生成一个错误(不正确的SQL语句),但我的问题是错误消息是通用的:

2017-08-25 09:19:28 - submit_scores.php:    Failed: SQLSTATE[42000]: Syntax 
error or access violation: 1064 You have an error in your SQL syntax; check 
the manual that corresponds to your MySQL server version for the right 
syntax to use near ',210,,      ,,,     )' at line 4

我可以看到问题,但我不想在循环中记录每个SQL语句,只需记录失败的FULL SQL语句。

任何帮助都将不胜感激。

2 个答案:

答案 0 :(得分:0)

你不应该在$counter块中重用catch变量和/或遍历所有的sql语句:你知道最后一个失败的语句是$sql[$counter]此时抛出异常。

因此,您应该只记录$sql[$counter]

,而不是循环遍历所有语句

答案 1 :(得分:0)

由于->exec()调用引发了异常,您可以将try / catch移动到循环中,然后只引用您调用的上一次尝试查询:

$conn->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$conn->beginTransaction();

for($counter=0;$counter<sizeof($sql);$counter++) {
    try {
        $query = $conn->prepare($sql[$counter]);
        $conn->exec($sql[$counter]);
    } catch (Exception $e) {
        echo "This is the query ($counter) that failed: " . $sql[$counter];
        $conn->rollBack();
        return;
    }
}
$conn->commit();