2017-08-25 54 views
1

我試圖找出try/catch失敗的完整SQL語句。下面是代碼:try/catch for循環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

'$ SQL [$計數器]'?而且你正在準備*和*執行一個單獨的查詢? – Qirel

回答

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(); 
+0

謝謝湯姆..那真棒! – chasiv

0

您不應該在catch塊中重複使用$counter變量,並且/或者對所有sql語句進行循環:您知道最後一條語句失敗,因爲在引發異常時爲$sql[$counter]

因此,您應該只記錄$sql[$counter]而不是遍歷所有語句。