如此处所示,如果存在与$ member_id匹配的数字ID,则该记录将被删除且$ res的计算结果为TRUE。如果表中包含' member_id'这是一个像abc1234这样的字符串,只有在我将$ member_id作为一个字符串包含在引号中时才会删除' $ member_id'将删除所有匹配,但是当$ res总是评估为TRUE时,如果不匹配,则不会删除任何内容(应该如此),但用户会获得" $ member_id。"已从会员表中删除"信息。我希望这很清楚。
<?php
$member_id = "";
require("connect.php");
if (isset($_POST['member_id']))$member_id = fix_string($_POST['member_id']);
$sql=("DELETE FROM members WHERE member_id = $member_id");
$res = mysqli_query($con,$sql);
**if($res) {
echo "member with ID of ".$member_id." has been removed from members table";
} else {
echo "member was not deleted";
}**
function fix_string($string) {
if (get_magic_quotes_gpc()) $string = stripslashes($string);
return htmlentities ($string);
}
?>
答案 0 :(得分:1)
您的逻辑位于正确的位置,但未正确执行。您正在尝试通过执行以下操作来查看是否已删除用户/成员:
$res = mysqli_query($con,$sql);
if($res) {
但是,如果语句针对true
正确执行,mysqli_query()
将返回DELETE
- 它是否删除行无关紧要。
您要做的是利用mysqli::$affected_rows
:
$res = mysqli_query($con, $sql);
if (mysqli_affected_rows($con) == 1) {
echo "member with ID of ".$member_id." has been removed from members table";
} else {
echo "member was not deleted";
}
这将检查是否有一条受DELETE
语句影响的记录(假设您的成员ID是唯一的;如果不是,则可以使用>= 1
代替)。如果有一个,那么它就被删除了!
旁注(不具体回答)
您应该放弃fix_string()
方法并选择mysqli
准备好的语句,这些语句会为您自动清理输入。您可以针对现有代码尝试以下操作:
require("connect.php");
$member_id = (!empty($_POST['member_id']) ? $_POST['member_id'] : '');
// prepare the statement
$stmt = mysqli_prepare($con, 'DELETE FROM members WHERE member_id = ?');
// bind the id
mysqli_stmt_bind_param($stmt, "s", $member_id);
// execute the statement
mysqli_stmt_execute($stmt);
if (mysqli_affected_rows($con) == 1) {
echo "member with ID of ".$member_id." has been removed from members table";
} else {
echo "member was not deleted";
}