[英]How can i delete from the database multiple rows using a checkbox?
i'm trying to delete from the database multiple rows using checkboxes. 我正在尝试使用复选框从数据库中删除多行。
I have an html table inside a foreach loop to seek the table values. 我在foreach循环中有一个html表来查找表值。
And i want to put a delete button inside this table to delete all the values from a certain row. 我想在此表中放置一个删除按钮,以删除特定行中的所有值。
But i dont know how to do that, i'm using this code: 但是我不知道该怎么做,我正在使用以下代码:
if (isset($_POST['delete']) && (!empty($_POST['checkbox']))){
$del_id = $_POST['checkbox'];
foreach($del_id as $value){
$sql = "DELETE FROM my_table WHERE id='".$value."'";
$result = mysql_query($sql);
}
}
And i have this code inside the foreach loop 我在foreach循环中有这段代码
<td><input style='width: 50px;' class='delete' value='delete' name='checkbox' type='checkbox'/></td>
<input type='hidden' name='id' value=".$key['job_id']." />
you need to change your this code from 您需要从以下位置更改此代码
<td><input style='width: 50px;' class='delete' value='delete' name='checkbox' type='checkbox'/></td>
to something like 像
<td><input style='width: 50px;' class='delete' value='delete' name='checkbox[]' type='checkbox'/></td>
see the difference between name='checkbox'
and name='checkbox[]'
and then in your php code .. write something like this 看到name='checkbox'
和name='checkbox[]'
之间的区别,然后在您的php代码中..编写如下内容
print_r($_POST);
you will get all the values .. try this . 您将获得所有值。尝试此操作。
You should treat the checkbox as an array: 您应该将复选框视为数组:
<input style='width: 50px;' class='delete' value='delete' name='checkbox[]' type='checkbox'/>
Also, instead of creating a new MySQL statement for each checkbox
value received, you can use the IN()
command: 另外,您可以使用IN()
命令,而不是为收到的每个checkbox
值创建新的MySQL语句:
if (isset($_POST['delete']) && (!empty($_POST['checkbox']))){
$del_ids = implode(',', $_POST['checkbox']);
$sql = "DELETE FROM my_table WHERE id IN('".$del_ids."')";
}
However, I strongly suggest using prepared statements. 但是,我强烈建议使用准备好的语句。 You also don't seem to sanitize the values in the $_POST
variable — very dangerous. 您似乎也没有清理$_POST
变量中的值,这很危险。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.