php update query won't update using pdo


php update query won't update using pdo

我有一个如下所示的edit.php文件。该页面通过GET['id']在表单中显示博客文章,以编辑该文章的标题和正文。当editPostForm被提交时,它应该用新的内容更新数据库,并重定向回/posts/页面。重定向可以工作,但是当查看文章时,博客文章没有任何变化。

我做错了什么?

$post = isset($_GET['id']) ? $_GET['id'] : '';
if (isset($_GET['id']))
{
    $id = $_GET['id'];
    $sql = "SELECT * FROM posts WHERE id = ?";
    $results = $db->prepare($sql);
    $results->bindValue(1, $id);
    $results->execute();
    $post = $results->fetch(PDO::FETCH_ASSOC);
}
if (isset($_POST['editPostForm']))
{
    $title = $_POST["title"];
    $body = $_POST["body"];
    $id = $_GET['id'];
    $stmt = $db->prepare("UPDATE posts SET title = ?, body = ? WHERE id = ?");
    $stmt->bindParam(1, $title);
    $stmt->bindParam(2, $body);
    $stmt->bindParam(3, $id);
    $stmt->execute(); 
    header("Location: posts");
}
$twigContext = array(
    "post" => $post
);
echo $twig->render('edit.html.twig', $twigContext);
HTML文件:

  <div class="wrapper">
    <form method="post" action="edit.php" class="editComposeForm">
      <h2>Edit Post</h2>
      <input type="text" value="{{ post.title }}" name="title"><br>
      <textarea name="body">{{ post.body }}</textarea><br>
      <input type="submit" value="Update" name="editPostForm">
    </form>
  </div>

html表单没有您试图在php代码中访问的带有名称id的输入。您可以将其添加为隐藏表单元素(下面的第一个示例),也可以将其添加为action属性中查询字符串的一部分(下面的第二个示例)。

添加为隐藏表单元素:

  <div class="wrapper">
    <form method="post" action="edit.php" class="editComposeForm">
      <input type="hidden" value="{{ post.id }}" name="id">
      <h2>Edit Post</h2>
      <input type="text" value="{{ post.title }}" name="title"><br>
      <textarea name="body">{{ post.body }}</textarea><br>
      <input type="submit" value="Update" name="editPostForm">
    </form>
  </div>

在php

$id = $_POST['id'];

或者将其添加到action属性中的查询字符串中。

  <div class="wrapper">
    <form method="post" action="edit.php/id={{ post.id }}" class="editComposeForm">
      <h2>Edit Post</h2>
      <input type="text" value="{{ post.title }}" name="title"><br>
      <textarea name="body">{{ post.body }}</textarea><br>
      <input type="submit" value="Update" name="editPostForm">
    </form>
  </div>

在php

$id = $_GET['id'];

表单没有id的输入,您的id'',这就是它不更新的原因。在您的表单中设置action="edit.php?id=somevalue"中的id,如<form method="post" action="edit.php?id={{ post.id }}" class="editComposeForm">