tags:

views:

65

answers:

4

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.

+2  A: 

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;
}
Erlend
I borrowed the count-test from YiSh, it's a good idea...
Erlend
Even better idea: return TRUE or FALSE. (So you can make tests like if($returnVariable)...)
christian studer
@chistian studier - Yes, I guess I got that idea while you was writing your comment.. ;)
Erlend
+3  A: 

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) .')';
}
YiSh
+1  A: 

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.

Michał Rudnicki
A: 

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

Paul Tarjan