我目前正在我的学院学习PHP,这是我很困惑的事情。我不知道如何使用HTML表单在PHP中创建下拉菜单以从数据库中删除行。这是我的代码:
//This is index.php
<div>
<?php
include('includes/delete.php');
?>
<form method="POST" action="includes/delete.php">
<select name="username">
<?php
$sql = mysqli_query($connection, "SELECT user_name, user_lastname FROM users");
while ($row = mysqli_fetch_assoc($sql)){?>
<option>
<?php echo $row['user_name'];?>
<?php echo $row['user_lastname'];?>
</option>
<?php }?>
</select>
<input type="submit" name="delete" value="Delete">
</form>
</div>
//This is delete.php
<?php
$serverName = "localhost";
$userName = "root";
$userPassword = "";
$dbName = "baza_podataka";
$connection = mysqli_connect($serverName, $userName, $userPassword, $dbName);
//Checking connection
if (!$connection) {
die("Error: Could not connect!" . mysqli_connect_error());
}
//Deleting an user from database
if(isset($_POST['delete'])) {
$username = $_POST['username'];
if(mysqli_query($connection, "DELETE FROM 'users' WHERE 'username' = '$username' " )){
echo "User was deleted!";
}else{
echo "User could not be deleted! Please try again later.";
}
}
答案 0 :(得分:0)
delete是按钮的ID,不会发布。您需要检查$ _post ['username']。
if(isset($ _ POST ['username'])){ $ username = $ _POST ['username']; ...
答案 1 :(得分:0)
代码中缺少的是option
标记内缺少select
值。同时,您的sql代码容易受到sql注入攻击,因此您应该使用bind参数。好的,您将使用以下代码片段来运行代码。
<option value="<?php echo $row['user_name']?>" >
<?php echo $row['user_name'];?>
<?php echo $row['user_lastname'];?>
</option>