将编辑按钮添加到表的每一行以更新 PHP 中的数据库
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21527946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Adding edit button to each row of table to update database in PHP
提问by user1597438
I've created a simple query of retrieving records from my database and passing it to a html. I want to add an edit/view button for each row so after some research, I ended up with this:
我创建了一个从数据库中检索记录并将其传递给 html 的简单查询。我想为每一行添加一个编辑/查看按钮,所以经过一些研究,我最终得到了这个:
$query = mysqli_query($con, "SELECT * FROM mytable") or die(mysqli_error($con));
if(mysqli_num_rows($query) > 0) {
while($row = mysqli_fetch_array($query)) {
echo "<tr><td>".$row['pId']."</td>";
echo "<td>".$row['data1']."</td>";
echo "<td>".$row['data2']."</td>";
echo "<td><form action='detailform.php' method='POST'><input type='hidden' name='tempId' value='".$row["pId"]."'/><input type='submit' name='submit-btn' value='View/Update Details' /><form></td>";
}
}
This works fine for 1 record. But if I have 2 or more, the latest record is always retrieved regardless of which record you selected. For example, if you have 5 records and you select any record, the 5th record will always be selected so I am unable to update the previous records. Why is this is happening? Am I missing something?
这适用于 1 条记录。但是如果我有 2 个或更多,无论您选择哪条记录,总是会检索最新的记录。例如,如果您有 5 条记录并且您选择了任何一条记录,那么第 5 条记录将始终被选中,因此我无法更新之前的记录。为什么会这样?我错过了什么吗?
Not sure if this helps my case but here's my the basic logic of my detailform.php:
不确定这是否对我的情况有帮助,但这是我的 detailform.php 的基本逻辑:
if(isset($_POST["tempId"]){
//pass data using post then update. Here's where I keep getting only the latest record regardless of selected record from previous page
} else { //add data }
回答by Florin Trifu
Close the form:
关闭表格:
echo "<td><form action='detailform.php' method='POST'><input type='hidden' name='tempId' value='".$row["pId"]."'/><input type='submit' name='submit-btn' value='View/Update Details' /></form></td></tr>";
The first one is sent correctly because it is the closest to the submit button, the rest will be closer to the last submit button
第一个正确发送,因为它最接近提交按钮,其余的将更接近最后一个提交按钮
回答by user1844933
try this
尝试这个
while($row = mysql_fetch_assoc($query)) {
echo "<tr><td>".$row['pId']."</td>";
echo "<td>".$row['data1']."</td>";
echo "<td>".$row['data2']."</td>";
echo "<td><form action='detailform.php' method='POST'><input type='hidden' name='tempId' value='".$row["pId"]."'/><input type='submit' name='submit-btn' value='View/Update Details' /></form></td></tr>";
}

