我有一些PHP和HTML代码,可从mysql数据库中获取ID,名称和状态。
使用按钮和$ _POST我试图在说用户按钮被单击时更新MYSQL数据库(这是一个简单的输入/输出面板)
这是我的代码
<?php
include 'confile.php';
if(isset($_POST['update'])) {
echo $_POST['update']. " "; //test to show correct name
echo $_POST['staffid']; //test to show the correct staffid << **THIS IS WHERE THE ISSUE IS**
//$incid = $_POST['staffid'];
//$sql = "SELECT status FROM staff WHERE id=$incid";
//$result = $conn->query($sql);
//echo $result; //show the status
} else {
//do nothing.
}
?>
<html>
<head>
<link rel="stylesheet" type="text/css" href="styles.css">
<title>Staff Board</title>
<body>
<div align="center" class="header">
<div class="header text">
<h1>Staff Board</h1>
</div>
<div class="header logo">
<img src="/assets/img/logo.gif" width="64px" height="64px">
</div>
</div>
<div id="conbox" align="center" class="content">
<hr>
<?php
//get all staff and their statuses
$sql = "SELECT id, firstname, surname, status FROM $staff ORDER BY surname ASC";
$result = $conn->query($sql);
while($row = $result->fetch_assoc()) {
// assign results to values
$id = $row["id"];
$firstname = $row["firstname"];
$surname = $row["surname"];
$status = $row["status"];
$fullname = $firstname . " " . $surname . " " . $id; //The $id variable will be dropped from here... it's just for testing. note, it works here, the correct ID is added to the button value
if ($status == 1) { //pick the correct color for the status
$color = "butGreen";
} else {
$color = "butRed";
}
?>
<form class="staffGrid" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]); ?>" method="POST">
<input type="hidden" id="staffid" name="staffid" value="<?php echo htmlspecialchars($id); ?>"/> <!-- hidden input to pass the id to $_POST -->
<input type="submit" id="update" name="update" value="<?php echo htmlspecialchars($fullname); ?>"/> <!-- submit button to trigger POST -->
</form> <!-- added as per devpro & billyonecan -->
<?php
};
?>
</div>
</div>
</body>
</html>
当我第一次加载页面时,按钮正确显示,并且在页面顶部没有期望的测试输出。
但是,当我单击一个按钮时,页面会正确刷新,并显示所按按钮的正确名称(来自第5行的回显),但是给出了错误的Staffid。它为while循环提供LAST id,而不是该按钮的正确值。
我假设对于每次迭代,将为该特定元素(按钮)设置值...显然我在这里是不正确的。
为什么会发生这种情况以及如何解决?
其他信息
Confile.php在代码中使用了以下变量:-
$conn = new mysqli($server, $username, $password);
$staff = [Location of db table]
一些输出:-
echo $sql;
SELECT id, firstname, surname, status FROM inout.staff ORDER BY surname ASC
echo print_r($_POST);
Array ( [staffid] => 17 [update] => First Second 8 )