As shown here if there is a numeric id that matches $member_id that record is deleted and $res evaluates to TRUE. If the table contains a 'member_id' that's a string such as abc1234 it will only delete if I make $member_id a string by enclosing it in quotes '$member_id' that will delete all matches but when then $res always evaluates to TRUE so if there is a mismatch nothing gets deleted(as it should) but the user gets a "$member_id." has been removed from members table" message. I hope that was clear.
<?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);
}
?>
Your logic is in the right place, but not executed correctly. You're trying to see if a user/member has been deleted by doing:
$res = mysqli_query($con,$sql);
if($res) {
However, mysqli_query()
will return true
if the statement executed properly for a DELETE
- it doesn't matter if it deletes rows or not.
What you'll want to do is utilize 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";
}
This will check if there was a single record affected by your DELETE
statement (assuming your member-IDs are unique; if not, you could use >= 1
instead). If there was one, well, it was removed!
Side Note (not answer specific)
You should drop your fix_string()
method and opt for mysqli
's prepared statements which will auto-sanitize the input for you. You can try the following for your existing code:
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";
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.