0

我在尝试通过 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有点陌生,我对此进行了研究,但没有提出任何解决方案。任何帮助是极大的赞赏!

4

1 回答 1

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);
于 2013-03-28T16:44:34.847 回答