在没有 mysqli_report 的情况下检查外键限制错误
Checking for foreign key restrictions errors without mysqli_report
对于以下评论(source)
PHP does not report mysqli or PDO errors by default because that information is highly sensitive, displaying it to a user is a great way to learn how to inject malicious data.
MYSQLI_REPORT_ERROR tells it to turn on the errors and MYSQLI_REPORT_STRICT tells it to convert those errors into Exceptions. This will give you a full report of the error message, so never do this in production environments.
如何检查生产中的外键约束错误以通知用户他或她在删除所有关联记录之前无法删除记录?
作为一般准则,exceptions should not be used for control flow。你应该做的是在 if
语句中保护你的 DELETE
语句,即:
<?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,在这种情况下您不再需要检查孤儿。
对于以下评论(source)
PHP does not report mysqli or PDO errors by default because that information is highly sensitive, displaying it to a user is a great way to learn how to inject malicious data.
MYSQLI_REPORT_ERROR tells it to turn on the errors and MYSQLI_REPORT_STRICT tells it to convert those errors into Exceptions. This will give you a full report of the error message, so never do this in production environments.
如何检查生产中的外键约束错误以通知用户他或她在删除所有关联记录之前无法删除记录?
作为一般准则,exceptions should not be used for control flow。你应该做的是在 if
语句中保护你的 DELETE
语句,即:
<?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,在这种情况下您不再需要检查孤儿。