I have a edit.php file as seen below. The page shows a blog post via GET['id'] in a form to edit the title and body of that post. When editPostForm is submitted, it should update the database with the new content and redirect back to the /posts/ page. The redirect works, but when viewing the post, nothing has changed about the blog post.
What am I doing wrong?
$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 File:
<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>
The html form does not have an input with the name id that you are attempting to access in the php code. You can add it either as a hidden form element (first example below) or as part of the query string in the action attribute (second example below).
Add it as a hidden form element:
<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>
And in the php
$id = $_POST['id'];
OR add it to the query string in the action attribute.
<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>
And in the php
$id = $_GET['id'];
表单没有输入id
,您的id
是''
,这是它不会更新的原因。在表单中,请在action="edit.php?id=somevalue"
设置ID,例如<form method="post" action="edit.php?id={{ post.id }}" class="editComposeForm">
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.