从数据库表中删除

时间:2016-03-03 21:04:58

标签: php pdo

我想让用户有可能删除其他用户。我创建了一个脚本,用户通过删除按钮获取所有用户的列表。按钮启动脚本但不从列表中删除用户。这是我的代码:

                                    function get_userlist(){
            $select_users = $this->db->prepare("SELECT user_id, fname, lname, email
                                            FROM user");
            $select_users->execute();

            echo "<tbody>";

            while($row = $select_users->fetch(PDO::FETCH_ASSOC)){
                echo "<form action='' method=''><tr><td>".$row["user_id"]."</td><td>".$row["fname"]."</td><td>
                ".$row["lname"]."</td><td>".$row["email"]."</td><td>
                <input type='hidden' name='user_id' value=".$row["user_id"] . " >
                <input type='submit' name='submit_delete' value='Delete'></td>
                </tr></form>";

            }
            echo "</tbody></table>";
        }

        function delete_user($user_id)
        {
            $delete_user = $this->db->prepare("DELETE FROM user WHERE user_id = :user_id");
            $delete_user->bindParam(':user_id', $user_id, PDO::PARAM_INT);
            $delete_user->execute();
        }

我使用这些功能的文件:

$user = new USER($con);
$user->get_userlist();

if(isset($_POST['submit_delete'])){
    $user_id = $_POST['user_id'];
    $user->delete_user($user_id);
}

我做错了什么?

1 个答案:

答案 0 :(得分:1)

您没有将$ user_id变量传递给delete_user函数。像这样编辑你的代码:

function delete_user($user_id)
{
        $delete_user = $this->db->prepare("DELETE FROM user WHERE user_id = :user_id");
        $delete_user->bindParam(':user_id', $user_id, PDO::PARAM_INT);
        $delete_user->execute();
}