使用PHP中的下拉菜单删除数据库中的数据

时间:2017-07-10 11:18:28

标签: php mysql mysqli

我正在努力用我的下拉菜单删除数据库中的数据。 我的下拉菜单看起来像这样

<form method="post" action="admin.php">
<h3>Delete a user</h3>
<select name="username">
$sql = mysqli_query($connection, "SELECT username FROM users");
while ($row = $sql->fetch_assoc()){
?>

<option value="username" name="username">
<?php echo $row['username']; ?></option>
<?php } ?>
<input type="submit" name="delete" value="Delete User">
</form>

这显示用户都很喜欢我想要它,所以这里是php for it

<?php 
include('connect.php');
if(isset($_POST['delete'])) {
$username = $_POST['username'];
mysqli_query("DELETE FROM `users` WHERE `username` = '$username' ");
echo "User was deleted!";
}
?>

因此,当我点击提交按钮&#34;删除用户&#34;时,看起来我被发送到admin.php并且没有任何反应。

我该如何解决这个问题? 感谢。

4 个答案:

答案 0 :(得分:2)

  1. name="username"替换为<option></option>
  2. 选项value中的回声值。
  3. admin.php 页面
  4. 中缺少连接变量

    更新代码

    <select name="username">
      <?php
      $sql = mysqli_query($connection, "SELECT username FROM users");
      while ($row = $sql->fetch_assoc()){?>
        <option value="<?php echo $row['username']; ?>"><?php echo $row['username']; ?></option>
      <?php }?>
    </select>
    

    <强> admin.php的

    mysqli_query($connection, "DELETE FROM `users` WHERE `username` = '$username' ");
    

答案 1 :(得分:1)

您没有将值放在选择选项中,这就是为什么没有发生任何事情 只需替换

<option value="username" name="username">
<?php echo $row['username']; ?></option>
<?php } ?>

<option value="<?php echo $row['username']; ?>">
<?php echo $row['username']; ?></option>
<?php } ?>

它适用于你。

答案 2 :(得分:1)

更改

<option value="username" name="username">
<?php echo $row['username']; ?></option>

<option value="<?php echo $row['username'] ?>" name="username">
<?php echo $row['username']; ?></option>

答案 3 :(得分:0)

1. <option value="username" name="username">需要<option value="<?php echo $row['username']; ?>">

2.缺少连接变量。需要: -

mysqli_query($connection,"DELETE FROM `users` WHERE `username` = '$username' ");

修改后的代码必须是: -

表格代码: -

<?php
//comment these two lines when code started working fine
error_reporting(E_ALL);
ini_set('display_errors',1);

include('connect.php');
?>
<form method="post" action="admin.php">
    <h3>Delete a user</h3>
    <select name="username">
      <?php
      $sql = mysqli_query($connection, "SELECT username FROM users");
      while ($row = mysqli_fetch_assoc($sql)){?>
        <option value="<?php echo $row['username']; ?>"><?php echo $row['username']; ?></option>
      <?php }?>
    </select>
<input type="submit" name="delete" value="Delete User">
</form>

Php代码: -

<?php
//comment these two lines when code started working fine
error_reporting(E_ALL);
ini_set('display_errors',1);

include('connect.php');
if(isset($_POST['delete'])) {
    $username = $_POST['username'];
    if(mysqli_query($connection,"DELETE FROM `users` WHERE `username` = '$username' ")){
        echo "User was deleted!";
    }
}
?>

注意: - 总是做一些error-reporting,这样你就会收到错误并纠正错误。

您的查询容易受SQL INJECTION影响,因此请阅读prepared statements并使用它们。