从复选框php和mysql中删除多个条目

时间:2016-03-20 11:50:49

标签: php mysql

我使用以下代码删除了用php编写的另一个页面的复选框和数组,但我一次只能删除1个条目

<?php
    $checked = "";
    $status  = (isset($_REQUEST['status'])); //Checks if any checkboxes have been selected
    if ($status == 'checked') {
        $status  = 1;
        $checked = 'checked="checked"'; 

        $value = $_POST['status']; //Uses the value of the checkbox

        foreach ($value as $val) { //Loops through all of the checkboxes that have been selected
            $sql = "DELETE FROM users WHERE ID='$val'"; //Mysql code to delete from the databases where items have been selected

            if ($conn->query($sql) === TRUE) { //If a value has been deleted 
                echo "Record deleted successfully: "; 
            } else {
                echo "Error deleting record: " . $conn->error; //Prints error if value hasnt deleted
            }
            $conn->close();//Closes sql connection
            echo $val; //Echos values selected
            echo '</br>';
        }
    } else {
        $status = 0;
    }
    echo <<<END
    END;
    ?>    

1 个答案:

答案 0 :(得分:0)

首先,您直接将发布的数据插入SQL查询 - 甚至是DELETE查询!恶意用户可以轻松利用此代码删除数据库的全部内容。

始终 转义SQL语句中使用的用户提交的值。

但直接问题是:您在执行第一个$conn->close()后立即致电DELETE。当您尝试执行第二次操作时,您的服务器连接已关闭。不要在你的循环之后给$conn->close()打电话。