使用复选框,PHP和MySQL删除多行
作者:互联网
正如标题所示,我想从我的数据库中删除多行.为了实现这一目标,我有两个文件,一个前端文件,它生成一个表,显示用户可以删除的文件,这些文件是使用复选框选择的.
后端文件用于处理选定的复选框,并使用SQL语句删除所选文件.
我遇到的问题是将所选文件的ID从前端传递到后端.这两个文件的代码如下:
前端
//Build Table Query
$query="SELECT * FROM documents";
$result= mysqli_query($con, $query) or die("Invalid query");
$count = mysqli_affected_rows($con);
?>
<table width="400" border="0" cellspacing="1" cellpadding="0">
<tr>
<td><form name="form1" method="post" action="deletefilesback.php">
<table width="800" border="0" cellpadding="3" cellspacing="2" bgcolor="#CCCCCC">
<tr>
<td colspan="5" bgcolor="#FFFFFF" align="center"><strong>Delete Multiple Files</strong></td>
</tr>
<tr>
<td align="center" bgcolor="#FFFFFF">#</td>
<td align="center" bgcolor="#FFFFFF"><strong>Id</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Title</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>Description</strong></td>
<td align="center" bgcolor="#FFFFFF"><strong>File Location</strong></td>
</tr>
<?php
while($row = mysqli_fetch_array($result)){
?>
<tr>
<td align="center" bgcolor="#FFFFFF"><input name="checkbox[]" type="checkbox" id="checkbox[]" value="<?php echo $rows['id']; ?>"></td>
<td bgcolor="#FFFFFF"><?php echo $row['id']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $row['title']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $row['description']; ?></td>
<td bgcolor="#FFFFFF"><?php echo $row['doc_link']; ?></td>
</tr>
<?php
}
?>
<tr>
<td colspan="5" align="center" bgcolor="#FFFFFF"><input name="delete" type="submit" id="delete" value="Delete Files"></td>
</tr>
</table>
</form>
</td>
</tr>
</table>
后端
$delete = $_POST['checkbox'];
//Then do what you want with the selected items://
foreach ($delete as $id) {
$query="DELETE FROM documents WHERE id = '".$id."'";
$result= mysqli_query($con, $query) or die("Invalid query");
}
//Show that the items have been successfully removed.//
if (mysqli_affected_rows($con) > 0) {
echo '<p>The selected items have been successfully deleted.</p>';
} else {
echo '<p>An error has occurred while processing your request</p>';
}
?>
作为一个注释,一旦这个工作,我将使用unlink函数使用前端表的doc_link部分删除服务器上的文件.
谢谢
解决方法:
在HTML页面中这样做
<input name="checkbox[<?php echo $row['id']?>]"
并在后端做这样的
foreach ($delete as $id => $val) {
if($val=='checked'){
$query="DELETE FROM documents WHERE id = '".$id."'";
$result= mysqli_query($con, $query) or die("Invalid query");
}
}
标签:php,mysql,sql-delete,drop-down-menu 来源: https://codeday.me/bug/20190927/1825007.html