0

我的 PHP 表单有问题。每当我刷新页面时,旧数据会自动插入到我的数据库中。我的代码是:

<?php
   if(isset($_GET['send'])){
      isset($_GET['name'])?$name = $_GET['name']:"";
      isset($_GET['score'])?$score = $_GET['score']:0;

      $con = mysql_connect('localhost','root','') or die(mysql_error());
             mysql_select-db('student',$con) or die(mysql_error());
      $qry = mysql_query('INSERT INTO student(name, score) VALUES('$name', $score)') or die(mysql_error());

      $display = mysql_query('SELECT * FROM student',$con) or die(mysql_error());
      echo '<table border=1>';
      while($rows = mysql_fetch_array($display)){
          echo '<tr>';
          echo "<td>$rows['id']</td>";
          echo "<td>$rows['name']</td>";
          echo "<td>$rows['score']</td>";
          echo '</tr>';
      } 
      echo '</table>';
    }
    ?>

请帮我解决这个问题。

4

3 回答 3

2

防止重复提交表单的一种常见方法是使用Post/Redirect/Get Pattern

然后,您需要将表单方法更改为Post。成功提交表单后,您再次重定向到表单,但将重定向设置为获取请求。然后表单将被重置(空值)。

编辑:

现在,正如我所见,您的脚本实际上可以执行类似的操作:插入 mysql 数据库后,您可以将其重定向到自身,删除 get 参数:

<?php
if(isset($_GET['send'])){
  isset($_GET['name'])?$name = $_GET['name']:"";
  isset($_GET['score'])?$score = $_GET['score']:0;

  $con = mysql_connect('localhost','root','') or die(mysql_error());
         mysql_select-db('student',$con) or die(mysql_error());
  $qry = mysql_query('INSERT INTO student(name, score) VALUES('$name', $score)') or die(mysql_error());
  header('Location: myscriptsurl.php');
  exit;
}

$display = mysql_query('SELECT * FROM student',$con) or die(mysql_error());
echo '<table border=1>';
while($rows = mysql_fetch_array($display)){
  echo '<tr>';
  echo "<td>$rows['id']</td>";
  echo "<td>$rows['name']</td>";
  echo "<td>$rows['score']</td>";
  echo '</tr>';
} 
echo '</table>';
?>
于 2011-07-06T10:04:22.267 回答
1

所以你有问题。而且由于您无法避免刷新屏幕...

如果您正在做表单发布,您可能会考虑在插入记录后发送位置标题:

<form action="process.php" method="POST">
<input type="text" name="number">
<input type="sumbit">
</form>

然后 from process.php: // 你是否通常根据帖子在数据库中插入

header("Location: http://www.example.com/thanks.php");
// do not forget the exit, since your script will run on without it.
exit;

这样,您的脚本将处理发布,然后将浏览器重定向到thanks.php. 重新加载thanks.php不会导致新的数据库插入。

于 2011-07-06T10:05:59.383 回答
1

你已经使用了 GET 方法,所以每次页面刷新它都会从 URL 中获取值。尝试使用 POST 方法...它将解决您的问题,并且不要忘记为 POST 设置条件

if(isset($_POST))
{
   /* Your Insert Code */

}
于 2011-07-06T10:14:06.080 回答