php更新查询赢得';t使用pdo更新
我有一个edit.php文件,如下所示。该页面通过GET['id']以编辑文章标题和正文的形式显示博客文章。提交editPostForm时,它应使用新内容更新数据库,并重定向回/posts/页面。重定向是有效的,但是在查看帖子时,博客帖子没有任何变化 我做错了什么php更新查询赢得';t使用pdo更新,php,mysql,pdo,Php,Mysql,Pdo,我有一个edit.php文件,如下所示。该页面通过GET['id']以编辑文章标题和正文的形式显示博客文章。提交editPostForm时,它应使用新内容更新数据库,并重定向回/posts/页面。重定向是有效的,但是在查看帖子时,博客帖子没有任何变化 我做错了什么 $post = isset($_GET['id']) ? $_GET['id'] : ''; if (isset($_GET['id'])) { $id = $_GET['id']; $sql = "SELECT *
$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>
编辑文章
{{post.body}}
html表单没有您试图在php代码中访问的名称id的输入。您可以将其添加为隐藏表单元素(下面的第一个示例)或作为操作属性中查询字符串的一部分(下面的第二个示例)
将其添加为隐藏的表单元素:
<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>
或者将其添加到操作属性中的查询字符串中
<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>
表单没有输入
id
,您的id
是'
,这就是它不更新的原因。在表单中,在action=“edit.php?id=somevalue”中设置id
就像
我认为应该从$stmt->bindParam
中的数字0开始,直接在MySQL中运行查询,看看它是否真的更新了?大多数情况下,where条件与任何记录都不匹配,因此不会进行更新。query直接在mysql中使用静态id@shawnkauffmanid
来自何处?已添加HTML文件。我认为GET是正确的,因为我显示的URL类似于:/edit?id=2。提交表单时,/edit?id=2 URL查询字符串将不存在。只有在显示帖子时,它才会出现。您需要将其添加到action属性中的表单中,或者将其作为隐藏项添加到表单中element@shawnkauffman-我很高兴它成功了,请接受我的回答。谢谢
<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>
$id = $_GET['id'];