2015-04-18 67 views
0

對於這樣的評論(source檢查外鍵約束錯誤,而mysqli_report

PHP因爲這些信息是高度敏感的默認不報告的mysqli或PDO的錯誤,它向用戶顯示是一個偉大的方式學習如何注入惡意數據。

MYSQLI_REPORT_ERROR告訴它打開錯誤,MYSQLI_REPORT_STRICT告訴它將這些錯誤轉換爲異常。這將爲您提供錯誤消息的完整報告,因此請勿在生產環境中執行此操作。

如何檢查生產中的外鍵約束錯誤以通知用戶他或她是否是,例如,在所有關聯記錄已被刪除之前無法刪除記錄?

回答

2

作爲一般指導,exceptions should not be used for control flow。你應該做的,而衛是你DELETE語句中if語句,即:

<?php 

$mysqli = new mysqli(/* blah */); 
$parent_id = /* id of parent record that we're trying to delete */; 

if ($stmt = $mysqli->prepare("select count(1) from child_table where parent_id = ?")) { 
    $stmt->bind_param("i", $parent_id); 
    $stmt->execute(); 
    $stmt->bind_result($child_row_count); 
    $stmt->fetch(); 
    $stmt->close(); 

    if ($child_row_count == 0) { 
     // there is no dependant object, so we can delete 
    } 
    else { 
     die("Can't delete object, it has child objects linked to it"); 
    } 
} 

?> 

另一種方法是使用cascading deletes to automatically remove child data,在這種情況下,您不再需要檢查孤兒。

+0

謝謝。最好是檢查準備或執行?與數據庫的實際通信在哪裏完成? – Talib