添加到数据库。刷新时不重复 [英] Adding to database. No repeat on refresh
问题描述
我有这个代码:
Episode.php
Episode.php
<?$feedback = new feedback;
$articles = $feedback->fetch_all();
if (isset($_POST['name'], $_POST['post'])) {
$cast = $_GET['id'];
$name = $_POST['name'];
$email = $_POST['email'];
$post = nl2br ($_POST['post']);
$ipaddress = $_SERVER['REMOTE_ADDR'];
if (empty($name) or empty($post)) {
$error = 'All Fields Are Required!';
}else{
$query = $pdo->prepare('INSERT INTO comments (cast, name, email, post, ipaddress) VALUES(?, ?, ?, ?, ?)');
$query->bindValue(1, $cast);
$query->bindValue(2, $name);
$query->bindValue(3, $email);
$query->bindValue(4, $post);
$query->bindValue(5, $ipaddress);
$query->execute();
} }?>
<div align="center">
<strong>Give us your feedback?</strong><br /><br />
<?php if (isset($error)) { ?>
<small style="color:#aa0000;"><?php echo $error; ?></small><br /><br />
<?php } ?>
<form action="episode.php?id=<?php echo $data['cast_id']; ?>" method="post" autocomplete="off" enctype="multipart/form-data">
<input type="text" name="name" placeholder="Name" /> / <input type="text" name="email" placeholder="Email" /><small style="color:#aa0000;">*</small><br /><br />
<textarea rows="10" cols="50" name="post" placeholder="Comment"></textarea><br /><br />
<input type="submit" onclick="myFunction()" value="Add Comment" />
<br /><br />
<small style="color:#aa0000;">* <b>Email will not be displayed publicly</b></small><br />
</form>
</div>
Include.php
Include.php
class feedback { public function fetch_all(){
global $pdo;
$query = $pdo->prepare("SELECT * FROM comments");
$query->bindValue(1, $cast);
$query->execute(); return $query->fetchAll();
} }
这个代码根据它来更新到数据库。但是在提交后,它会重新加载当前页面,如表单操作中所述。
This code updates to the database as it is suppose to. But after submission it reloads the current page as mentioned in the form action.
但是当我刷新页面以查看添加的评论时,它要求重新提交。如果我提交,则该评论再次添加。
But when I refresh the page to see the comment being added it asks to re submit. If I hit submit then the comment adds again.
如何阻止这种情况发生?
How can I stop this from happening?
也许我可以隐藏评论框并显示谢谢消息,但不会停止重复输入。
Maybe I could hide the comment box and display a thank you message but that would not stop a repeat entry.
请帮忙。谢谢。
Kev
推荐答案
您需要在其中添加重定向。因此,在POST块的底部添加
You need to add a redirect in there. So at the bottom of your POST block add
if(isset($_POST['name'], $_POST['post'])) {
// Do POST stuff here
header('Location: your/url/here');
exit;
}
这将发送一个302重定向到浏览器,它执行一个干净的负载页。由于这是一个GET操作,所以也没有重新加载问题。
This sends a 302 redirect to the browser and it does a clean load of the page. Since this is a GET operation, there's no reload issues either.
这篇关于添加到数据库。刷新时不重复的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!