0

I have a similar problem with delete command too..

    function deleteUsers($userID) {

    foreach($userID as $key => $val)
        {

  $query = "DELETE FROM members WHERE member_id = '$val'";
  $result = mysql_query($query);

            }

   //$query = "DELETE FROM members WHERE member_id = $userID";
   //$result = mysql_query($query);

   if($result) 
   {
       return 'yes';
    }

    }

its not performing multi delete.... the $userID contains array. Its not going inside the Query.

4 Answers 4

3

When using multiple IDs use variable IN (1,2,3) format rather than simple equality. Also if you have more than one ID maybe the variable should be called $userIDs?

if(count($userID) > 0) {
  $query = 'DELETE FROM members WHERE member_id IN ('. implode(',', $userID) .')';
}
Sign up to request clarification or add additional context in comments.

Comments

2

Without foreach:

function deleteUsers($userID) {
    if (count($userID)) {
        $query = "DELETE FROM `members` WHERE `member_id` IN (".implode(",", array_values($userID)).");";
        if (mysql_query($query)) { return true; }
    }
    return false;
}

2 Comments

Even better idea: return TRUE or FALSE. (So you can make tests like if($returnVariable)...)
@chistian studier - Yes, I guess I got that idea while you was writing your comment.. ;)
1

This will make the function to understand array as well as single integer:

function deleteUsers($u) {
    $condition = is_array($u)
        ? "member_id IN (" . implode(',', $u) . ")"
        : "member_id = " . (int)$u;
    $res = mysql_query("DELETE FROM `members` WHERE $condition");
    return $res ? true : false;
}

Remember that your parameters are not properly escaped and cannot be trusted. To learn more on escaping SQL and preventing injection attacks read about Prepared Statements.

Comments

0

Please, for the love of the internet, don't built an SQL query yourself. Use PDO.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.