我有一个表,它显示从 mysql 中的 2 个不同表中提取的数据。该表的每一行都有一个删除按钮,当按下该按钮时,将发送运行删除查询,该查询将删除该行以及数据库中的所有相关数据。
但是,无论我单击哪个删除按钮,删除的始终是表中的最后一行,而不是删除按钮所在的行。
我的桌子:
-------------------------------------------
|Username|Password|Branch Name|Branch Info|
----------------------------------------------------
|Sub1 |Pass1 |branch1 |1st branch |DELETE |
----------------------------------------------------
|Sub2 |Pass2 |branch2 |2nd branch |DELETE |<---this button is pressed
----------------------------------------------------
|Sub3 |Pass3 |branch3 |3rd branch |DELETE |
----------------------------------------------------
|Sub4 |Pass4 |branch4 |4th branch |DELETE |
----------------------------------------------------
|Sub5 |Pass5 |branch5 |5th branch |DELETE |<---this row is deleted.
----------------------------------------------------
我的代码:
<?PHP
session_start();
if(@$_SESSION['Auth']!=="Yes" AND @$_SESSION['Type']!=="Admin")
{
echo"You are not authorised to view this page.Please click <a href='Login.php'>here</a> to login.";
exit();
}
?>
<?PHP
if(@$_POST['deluser']=="Delete")
{
include("cxn.inc");
print_r($_POST);
$id="$_POST[id]";
echo"$id";
if(empty($_POST["id"]))
echo"yep";
$deluser="DELETE FROM SubUsers WHERE SubUsers.id='$id'";
$delquery=mysqli_query($cxn,$deluser) or die (mysqli_error($cxn));
$delsuccess="Deletion successful";
}
>
<html>
<head><link rel="stylesheet" type="text/css" href="style.css" /></head>
<body>
<?PHP
include("cxn.inc");
//include("AdminNav.php");
$viewuser="SELECT SubUsers.Id,Username,Password,Name,Info FROM SubUsers,Branch WHERE SubUsers.id=Branch.id AND SubUsers.Userid='$_SESSION[UserId]'";
$runuser=mysqli_query($cxn,$viewuser) or die(mysqli_error($cxn));
$rows=array();
while($row=mysqli_fetch_assoc($runuser))
$rows[]=$row;
echo"<form action='$_SERVER[PHP_SELF]' name='DelUser' method='POST' >";
echo"<table border='1'>";
echo"<tr>";
echo"<td>";
echo"Username";
echo"</td>";
echo"<td>";
echo"Password";
echo"</td>";
echo"<td>";
echo"Branch Name";
echo"</td>";
echo"<td>";
echo"Branch Info";
echo"</td>";
echo"</tr>";
foreach($rows as $row)
{
$id=$row['Id'];
echo"$id";
echo"<tr>";
echo"<td>";
echo"$row[Username]";
echo"</td>";
echo"<td>";
echo"$row[Password]";
echo"</td>";
echo"<td>";
echo"$row[Name]";
echo"</td>";
echo"<td>";
echo"$row[Info]";
echo"</td>";
echo"<td>";
echo"<input type='hidden' name='id' value='$id' >";
echo"<input type='Submit' name='deluser' value='Delete' >";
echo"</td>";
echo"</tr>";
}
echo"<tr>";
echo"<td colspan='5'>";
if(isset($delsuccess))
{echo"$delsuccess";}
echo"</td>";
echo"</tr>";
echo"</table>";
echo"</form>";
?>
</body>
</html>
线
回声“$id”;
在 foreach 循环下成功地返回每一行的 id,因为每一行都被输出到屏幕上。
按下 DELETE 按钮后,该行
print_r($_POST);
输出 $_POST 中的所有变量,给出结果
Array ( [id] => x [deluser] => Delete )
其中 x 是表中最后一行的 id(例如,如果表中有 5 行,则 x=5)
问题 为什么 DELETE 按钮只传递最后一行的 id,而不是它所在行的 id?另外,我该怎么做才能做到这一点,以便当按下删除按钮时,只有删除按钮旁边的行是否被删除?
在过去的 2 个小时里,我一直在看这个,但仍然无法弄清楚我错在哪里;该代码显然正在工作,因为按下删除按钮时正在删除行,但是只是删除了错误的行。
任何帮助将不胜感激。谢谢