0

我正在使用 SQL 语句学习 PHP,但在尝试创建删除按钮时遇到了问题。

问题是当我按下“删除”按钮时什么都没有发生。查询运行正常,它从循环中获取正确的用户 ID。

<?php
        require_once 'db_connect.php';

        $select = "SELECT * FROM Users";
        $result = mysqli_query($dbc, $select) or die('could not query database');


        while ($row = mysqli_fetch_assoc($result)) {

            echo '
            <tr>
                <td>' . $row['userid'] . '</td>
                <td>' . $row['fnamn'] . ' ' . $row['enamn'] . '</td>
                <td>' . $row['username'] . '</td>
                <td>' . $row['email'] . '</td>
                    <td>' . '<form action="" method="post">
                            <input type="button" name="delete" value="Radera" />
                        </form>' . '</td>

            </tr>';

            if(isset($_POST['delete'])) {

                $userid = $row['userid'];

                $delete = "DELETE FROM Users WHERE userid = '$userid' ";
                $result = mysqli_query($dbc, $delete) or die('could not query database');
            }
        }

        mysqli_close($dbc);
        ?>
4

2 回答 2

2

你需要:

  1. 将您的if (isset($_POST['delete']))语句放在while循环之外和之前。
  2. 有一些方法可以知道您删除了哪一行(可能使用隐藏的输入)。

像这样的东西:

<?php
require_once 'db_connect.php';

if(isset($_POST['delete']) && isset($_POST['user_id'])) {
    $userid = $_POST['user_id'];

    $delete = "DELETE FROM Users WHERE userid = '$userid' ";
    $result = mysqli_query($dbc, $delete) or die('could not query database');
}

$select = "SELECT * FROM Users";
$result = mysqli_query($dbc, $select) or die('could not query database');

while ($row = mysqli_fetch_assoc($result)) {
    echo '
    <tr>
        <td>' . $row['userid'] . '</td>
        <td>' . $row['fnamn'] . ' ' . $row['enamn'] . '</td>
        <td>' . $row['username'] . '</td>
        <td>' . $row['email'] . '</td>
        <td>' . '<form action="" method="post">
            <input type="hidden" name="user_id" id="user_id" value="'.$row['userid'].'" />
            <input type="submit" name="delete" id="delete" value="Radera" />
        </form>' . '</td>
    </tr>';
}

mysqli_close($dbc);
?>

我不建议您$_POST['user_id']像上面那样直接插入查询;你会想要阅读准备好的陈述

于 2013-01-05T01:39:30.937 回答
1

更换类型。

代替:

<input type="button" name="delete" value="Radera" />

尝试:

<input type="submit" name="delete" value="Radera" />
于 2013-01-05T01:28:37.047 回答