我正试图编写一段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'); */
[MY 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>
正如@ADyson在他们的评论中分享的那样,除了mysql
和phpmyadmin
之间的混淆之外,还有一些事情需要解决。
-
要删除一行,需要使用
DELETE
mysql语句。TRUNCATE
是错误的,因为它删除了表中的所有行。阅读官方文档了解更多信息。 -
将
POST
数据的管理移到while
循环之外,否则您将多次运行该代码 -
您不会以任何方式通过
POST
传递ID。一个简单的方法是将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>