这里混合了HTML和PHP。我没有将它们分开,因为标签是由php填充的。
<form method="post">
<select name="Select User" value="Select User">
<?php
$sth = $conn->prepare('Select username From users');
$sth->execute();
$data = $sth->fetchAll();
foreach ($data as $row ){
if($row['username']!="")
echo " <option id=\"Select_user\" name=\"Select_user\" value=\"Select_user\">".$row['username']."</option>";
}
?>
</select><br>
<input type="submit" name="submit" value="Delete"</input>
<?php
if(! empty($_POST['Select_user']))
{
$del_user=$_POST['Select_user'];
$sql = "DELETE FROM users WHERE username=:del";
$sth = $conn->prepare($sql);
$sth->execute(array(':del'=>$del_user));
}
?>
下拉列表正在正确获取数据,但删除操作没有发生。为什么呢?
答案 0 :(得分:-1)
您需要在将在php中发布的选项值中设置正确的数据,选择的选项值将被发布,因此您需要$ _POST中的用户名,因此在选项值中设置用户名:
<form method="post">
<select name="user_selection">
<?php
$sth = $conn->prepare('Select username From users');
$sth->execute();
$data = $sth->fetchAll();
foreach ($data as $row ){
if($row['username']!="")
echo '<option id="Select_user" name="Select_user" value="'.$row["username"].'">'.$row["username"].'</option>';
}
?>
</select><br>
<input type="submit" name="submit" value="Delete"</input>
<?php
if(! empty($_POST['user_selection'])) // access element by its name
{
$del_user=$_POST['user_selectio'];
$sql = "DELETE FROM users WHERE username=:del";
$sth = $conn->prepare($sql);
$sth->execute(array(':del'=>$del_user));
}
?>