php - 为什么给出最后一次迭代,而不是当前迭代?
问题描述
我有一些 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 )
解决方案
解决方案是确保结束标记出现在代码中,并且在正确的位置,以防止错误的迭代!
推荐阅读
- c# - 是否可以立即停止 threading.Timer?
- sql - 在单个子句中使用 IN 进行多个连接
- html - 仅在收到 get 函数的响应后,如何使用 Angular 生成 HTML 页面
- swift - 如何在 Swift 中解决“无法推断通用参数'T'”
- python - 从python中的列表列表中提取列表
- c++ - 在循环内调用 MPI_Reduce 时出现致命错误
- mysql - 创建跨多个列具有相互唯一性的表
- c++ - 为什么编译行错误导致无法找到头文件
- python-3.x - Pyhon 记录 TimedRotatingFileHandler 日志文件锁定功能
- c++ - 错误:变量“Point a”具有初始化程序但类型不完整。我的代码有什么问题?