提问人:ubuntu-user 提问时间:6/26/2021 最后编辑:ubuntu-user 更新时间:6/26/2021 访问量:1094
如何为表格中的每一行创建一个删除按钮?
How to create a delete button for each row in the table?
问:
我正在尝试编写一个PHP代码,该代码从mySQL连接并获取数据单元格,并为每一行创建一个删除按钮,因为它像在mySQL数据库中一样增加。
请帮我弄清楚我做错了什么?!!
[我的表名是“VF”,其结构是这样的]
ID Password1 Password2
[我使用的PHP变量是]
$Connect=mysqli_connect($host,$user,$Pass,$db);
$QueryVF = mysqli_query($Connect,'SELECT * from vf');
$ID =$_POST['ID'];
$DelVF = mysqli_query($Connect,'DELETE from vf where ID =$ID');
/* ALSO TRIED This: $DelVF = mysqli_query($Connect,'TRUNCATE vf'); */
[我的HTML和PHP代码]
<html>
<body>
<form method="POST">
<table border="1" class=".input"> <!--vf Table-->
<tr>
<th>ID</th>
<th>Password 1</th>
<th>Password 2</th>
<th>Drop data</th>
</tr>
<?php
while ( $row = mysqli_fetch_array($QueryVF)){
echo'<tr>';
echo'<td>'.$row['ID'].'</td>';
echo'<td>'.$row['Password1'].'</td>';
echo'<td>'.$row['Password2'].'</td>';
echo "<td><button type=\"submit\" name=\"Delete\" oneclick=\"$DelVF\">Drop Data</button></td>";
if($_POST['Delete']){
while ($DelVF = mysqli_query($Connect,"'DELETE from vf where ID =$ID'") )
$DelVF;
echo "VF table's row is successfully deleted";
}
echo'</tr>';
}
?>
</table>
</form>
</body>
</html>
答:
2赞
Andrea Olivato
6/26/2021
#1
正如@ADyson在他们的评论中分享的那样,除了 和 之间的混淆之外,还有一些事情需要解决。mysql
phpmyadmin
要删除一行,您需要使用 mysql 语句。 是错误的,因为它会从表中删除所有行。有关详细信息,请阅读官方文档。
DELETE
TRUNCATE
将数据管理移到循环之外,否则将多次运行该代码
POST
while
您不会以任何方式传递 ID。一个简单的方法是将属性添加到按钮,如下所示:
POST
value
submit
echo '<button type="submit" name="Delete" value="'.$row['ID'].'">Drop Data</button>';
总体而言,请参阅下面的完整代码和注释,以指导您理解为什么需要更改:
// Manage the POST data at the top of your file
if (isset($_POST['Delete'])) {
// If you receive the Delete post data, delete it from your table
$delete = 'DELETE FROM vf WHERE ID = ?';
$stmt = $Connect->prepare($delete);
$stmt->bind_param("i", $_POST['Delete']);
$stmt->execute();
}
// Run your select AFTER the DELETE, so that you will get the updated table
$QueryVF = mysqli_query($Connect, 'SELECT * from vf');
?>
<html>
<body>
<form method="POST">
<table border="1">
<tr>
<th>ID</th>
<th>Password 1</th>
<th>Password 2</th>
<th>Drop data</th>
</tr>
<?php
while ($row = mysqli_fetch_array($QueryVF)) {
echo'<tr>';
echo'<td>'.$row['ID'].'</td>';
echo'<td>'.$row['Password1'].'</td>';
echo'<td>'.$row['Password2'].'</td>';
// Add the ID to the value attribute so that it gets passed via POST
echo '<td><button type="submit" name="Delete" value="'.$row['ID'].'">Drop Data</button></td>';
echo'</tr>';
}
?>
</table>
</form>
</body>
</html>
评论
0赞
ubuntu-user
6/26/2021
非常感谢,它有效,但我仍在努力了解它是如何工作的。
0赞
Sadikul Haque Sadi
3/20/2022
它工作得很好。但是也有效。mysqli_query($Connect, "delete from vf where ID='$_POST[Delete]'") or die(mysqli_error($Connect));
1赞
Andrea Olivato
3/21/2022
@SadikulHaqueSadi不,它没有。该代码使应用程序对 SQL 注入广泛开放。在这里阅读
评论