我在尝试通过php填充的下拉菜单更新数据库中的多个条目时遇到问题。这是我页面上填充表格的代码,显示我目前在我的数据库中的所有条目:
$result = mysqli_query($con,"SELECT * FROM Submissions");
echo "<table border='1'>
<tr>
<th>First name</th>
<th>Last name</th>
<th>Email</th>
<th>Title</th>
<th>Text</th>
<th>Public Post OK?</th>
<th>Date/Time Submitted</th>
<th>Approved?</th>
<th>Test Approved</th>
</tr>";
while($row = mysqli_fetch_array($result))
{
echo "<tr>";
echo "<td>" . $row['fname'] . "</td>";
echo "<td>" . $row['lname'] . "</td>";
echo "<td>" . $row['email'] . "</td>";
echo "<td>" . $row['title'] . "</td>";
echo "<td>" . nl2br($row['text']) . "</td>";
echo "<td>" . $row['publicpost'] . "</td>";
echo "<td>" . $row['time'] . "</td>";
echo "<td><select name=\"approved\"><option value=\"" . $row['approved'] . "\">" . $row['approved'] . "</option><option value=\"yes\">Yes</option><option value=\"no\">No Again</option></select></td>";
echo "<td>" . $row['approved'] . "</td>";
echo "</tr>";
}
echo "</table>";
?>
<br><br>
<form action="update.php" method="post">
<input type="submit" name="SubmitButton" value="Update" class="submit" style="cursor:pointer;">
</form>
<?php
mysqli_close($con);
?>
这是“update.php”的php代码:
$approved = $_POST['approved'];
mysqli_query($con,"UPDATE Submissions SET approved = $approved");
$update_query= "UPDATE Submissions SET approved = '$approved'";
if(mysqli_query($con,$update_query)){
echo "updated";}
else {
echo "fail";}
?>
<form action="approvesubmissions.php">
<input type="submit" value="Approve Submissions page">
</form>
目标是能够使用下拉菜单将“已批准”字段从“否”更新为“是”,反之亦然。相反,此查询发生的是它正在删除“已批准”字段中的数据而不是更新它。我对php有些新手,我已经研究了TON并且没有找到解决方案。非常感谢任何帮助!
答案 0 :(得分:0)
首先,让我们假设'已批准'是TINYINT(1)或其他东西。
你的选择html应该更像这样。它将根据DB值自动填充。
$selected = 'selected="selected"'; // pre-selection attribute
$isApproved = !!$row['approved']; // is this active? (approved is 1 or 0)
echo '<select name="approved">
<option value="1" ' . ($isApproved ? $selected : '') . '>Yes</option>
<option value="0" ' . (!$isApproved ? $selected : ''). '>No</option>
</select>';
其次,您的表单位于表格的底部,但您想要的输入位于表格中。当您提交表单时,没有$ _POST ['approved'],因为这在技术上不在表单中。要修复,您需要将开始表单标记放在表格前面的顶部。然后,在您回显表格之后,您将要在结尾处放置提交按钮和结束表单标记。
第三,你的post.php页面不应该直接将用户输入带入查询。但是,只需这样做:
// Convert input to boolean answer, then int (for the query).
$approved = isset($_POST['approved']) ? (int)!!$_POST['approved'] : 0;
mysqli_query($con,"UPDATE Submissions SET approved = '$approved'");
虽然我们正在谈论这个话题,但现在是进入项目预备语句的好时机。这可能听起来很吓人,但它可以让你免于SQL注入。
// Make the prepared statement
$query = mysqli_prepare("UPDATE Submissions SET approved = ?");
// Safely bind your params
mysqli_stmt_bind_param($query, "i", $approved);
// Run it
mysqli_stmt_execute($query);
// "close" the statement (hint: it's reusable for things like bulk updates, etc)
mysqli_stmt_close($query);