1

如此处所示,如果存在与 $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);
}
?>
4

1 回答 1

1

您的逻辑在正确的位置,但未正确执行。您正在尝试通过执行以下操作查看用户/成员是否已被删除:

$res = mysqli_query($con,$sql);
if($res) {

但是,如果语句为 a 正确执行,mysqli_query()将返回- 是否删除行无关紧要。trueDELETE

你想要做的是利用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";
}
于 2012-11-16T05:01:08.513 回答