从PHP中的表中多次删除

时间:2014-10-27 13:22:44

标签: php mysql

我想删除组中的多个成员, if语句成功分配来自单个组的多个成员,但Deletion(ifelse)仅删除一个成员!

if( isset( $_POST['add_member'] ) )
    {
        $group_id = $_POST['group_id'];

        foreach ($_POST['member_id'] as $member) {

         $query="SELECT id FROM member_group
                    WHERE member_id = $member AND `group_id` =  $group_id[0]";
        if(!mysqli_num_rows(mysqli_query($connection,$query)))
        {
            $query="INSERT INTO `member_group`(member_id,group_id)                                                                       VALUES($member,$group_id[0])";
            mysqli_query($connection,$query) or die(mysqli_errno($connection));
        }
           echo "<div class='alert alert-info'>Member Assigned. </div>";
        }
    }
    elseif( isset( $_POST['remove_member'] ) )
    {
         $member_id = $_POST['member_id'];

         foreach ($_POST['group_id'] as $group) {
            $query="DELETE FROM member_group
                WHERE group_id = $group AND `member_id` =  $member_id[0]" ;
         $rows = mysqli_query($connection,$query);

谢谢!

1 个答案:

答案 0 :(得分:1)

如果您要删除该群组的所有成员,请从查询中删除member_id的条件

$query="DELETE FROM member_group WHERE group_id = $group" ;

或者,如果您要删除所选成员,则必须从帖子中提取每个成员,如

$member_arr = explode(',',$_POST['member_id']);
foreach ($member_arr as $member) {
    $query="DELETE FROM member_group
            WHERE `member_id` =  $member" ;
}

如果$member_id[0]包含您在评论中提到的多个值,那么您可以使用IN编写查询

$query="DELETE FROM member_group
            WHERE `member_id` IN (".$member_id[0].") " ;

考虑到$member_id[0]的格式为1,2,3,4,5,6,如果它是array格式,则必须使用IMPLODE

$query="DELETE FROM member_group
            WHERE `member_id` IN (".implode(',',$member_id[0]).") " ;