我正在尝试从表单中的复选框中删除电子邮件条目,但它无法从'todelete[]'
数组中获取任何值
这是代码:
<?php
$dbc= mysqli_connect('localhost','root','','customer_base')or die('Error connecting to MySQL server.');
$query = "select * from email_list";
$result= mysqli_query($dbc, $query)or die('Error querying database.');
while($row= mysqli_fetch_array($result)){
echo '<input type="checkbox" value="' .$row['id']. '"name="todelete[]" />';
echo $row['first_name'].' '.$row['last_name'].' '.$row['email'].' '.'<br />';
}
if((isset($_POST['submit']))&&(isset($_POST['todelete']))){
$output_form= false;
foreach($_POST['todelete'] as $delete_id){
$query = "delete from email_list where id = $delete_id";
mysqli_query($dbc,$query)or die('Error querying database.');
}
echo '<p>Customer entry removed</p>'.'<br />';
}elseif((isset($_POST['submit']))&&(empty($_POST['todelete']))){
echo "<p>you haven't selected any customer entry to delete!</p>";
$output_form= true;
}else {$output_form= true; }
mysqli_close($dbc);
if($output_form){
?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<input type="submit" name="submit" value="remove" />
</form>
<?php
}
?>
现在,如果没有选中复选框,它会给出消息,选中复选框,但即使选中了复选框,它仍会返回消息以选中复选框。
因此,它永远不会进入删除查询的循环,而$_POST['todelete']
始终为空,但它不应该。你试图检查$_POST
数组是否为空,它没有任何结论,
我试图通过很多答案,但似乎我的查询尚未解决......需要帮助!!
我在使用代码做错了什么?
答案 0 :(得分:0)
您的复选框似乎在表单标记之外。 只需用下面的代码替换您的代码:
//check for $_POST values
if((isset($_POST['submit']))&&(isset($_POST['todelete']))){
$output_form= false;
foreach($_POST['todelete'] as $delete_id){
$query = "delete from email_list where id = $delete_id";
mysqli_query($dbc,$query)or die('Error querying database.');
}
echo '<p>Customer entry removed</p>'.'<br />';
}elseif((isset($_POST['submit']))&&(empty($_POST['todelete']))){
echo "<p>you haven't selected any customer entry to delete!</p>";
$output_form= true;
}else {
$output_form= true;
}
//check if to show form
if($output_form){ ?>
<form action="<?php echo $_SERVER['PHP_SELF']; ?>" method="post">
<?php
$dbc= mysqli_connect('localhost','root','','customer_base')or die('Error connecting to MySQL server.');
$query = "select * from email_list";
$result= mysqli_query($dbc, $query)or die('Error querying database.');
while($row= mysqli_fetch_array($result)){
echo '<input type="checkbox" value="' .$row['id']. '"name="todelete[]" />';
echo $row['first_name'].' '.$row['last_name'].' '.$row['email'].' '.'<br />';
}
mysqli_close($dbc);
?>
<input type="submit" name="submit" value="remove" />
</form>
<?php } ?>
因为我可以看到你正在使用mysqli,我建议你继续使用PDO。