我以前在写 PHP 程序时,经常碰到页面刷新时,数据库多处理一次的情况。
我们来看 addcust.php:
<?php
$query = "INSERT INTO customer
SET surname = $surname,
firstname = $firstname";
$connection = mysql_connect("localhost", "fred", "shhh");
mysql_select_db("winestore", $connection);
$result = mysql_query($query, $connection);
?>
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<title>Customer insert</title>
</head>
<body>
I've inserted the customer for you.
</body>
</html>
?>
假设我们用下面的连接使用这个程序:
http://www.freelamp.com/addcust. ... &firstname=Fred
如果这个请求只提交一次,OK ,不会有问题,但是如果多次刷新,你就会有多条记录插入。
这个问题可以通过 header() 函数解决:下面是新版本的 addcust.php:
<?php
$query = "INSERT INTO customer
SET surname = $surname,
firstname = $firstname";
$connection = mysql_connect("localhost", "fred", "shhh");
mysql_select_db("winestore", $connection);
$result = mysql_query($query, $connection);
header("Location: cust_receipt.php");
?>
这个脚本把浏览器重定向到一个新的页面:cust_receipt.php:
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<title>Customer insert</title>
</head>
<body>
I've inserted the customer for you.
</body>
</html>
这样,原来的页面继续刷新也没有副作用了。