【发布时间】:2017-04-14 19:52:47
【问题描述】:
我目前正在开发一个用 PHP 制作的博客网站,我正在尝试制作一个表单来更新预先存在的博客文章。由于这是一个更新,我希望在打开表单时预先填充旧内容,因此我将值设置为包含我正在编辑的帖子的标题和内容的变量。问题是当这个值被设置时,如果我按下提交编辑的文本没有被传递到数据库中,它仍然传递我开始时的相同值。 sql 查询应该没问题,因为如果我在没有设置值的情况下打开表单,我可以覆盖有问题的博客文章而不会出现任何问题。我在想它可能是 $_POST 变量没有在正确的时间更新并获取预设值而不是输入的值。我该如何解决这个问题?
这是发布功能:
if (isset ($_POST['btn-post'])){
//getting rid of whitespace
$title = trim($_POST['title']);
$content = trim($_POST['content']);
$ID = $postID;
// $tags = trim($_POST['tags']);
if (empty ($title)){
$error[] = "Please enter a title.";
}
if (empty($content)) {
$error[] = "Please enter some text.";
}
if (strlen($title) > 250) {
$errors = 'Please shorten your title, it is too long (250 character limit).';
}
if (strlen($content) > 2000) {
$errors = 'Please shorten your blog post, it is too long (2000 character limit).';
}
else {
$post->updatePost($title, $content, $ID);
header('Location: index.php');
exit;
}
}
查询如下:
public function updatePost($title,$content,$postID)
{
try
{$stmt = $this->db->prepare("UPDATE posts
SET post_title = :post_title, post_content = :post_content
WHERE post_id=:post_id");
$stmt->bindParam(":post_title", $title);
$stmt->bindParam(":post_content", $content);
$stmt->bindParam(":post_id", $postID);
$stmt->execute();
return $stmt;
}
catch(PDOException $e)
{
echo $e->getMessage();
}
}
这是带有预设值的帖子表单($postTitle 和 $postValue 在另一个文件中定义):
<form class ="col-sm-8 well well-lg" action="" method="post">
<div class="form-group">
<label for="title">Title</label>
<input class="form-control" type="text" name="title" value="<?= $postTitle ?>">
</div>
<div class="form-group">
<label for="content"> Content </label>
<textarea class="form-control" name="content" rows="10"><?= $postContent ?></textarea>
</div>
<div>
<input type="submit" value="Update Post" name="btn-post">
</div>
</form>
【问题讨论】:
标签: php forms post sql-update submit