<?php 
// 数据库功能 
// 重定向 
header("Location: $HTTP_REFERER"); 
exit; 
?> 
这里有两个常见的错误需要提醒一下:
调用 header() 函数后要包含一个 exit 语句让脚本停止,否则后续的脚本可能会在头发送前输出。
header() 函数常见的一个错误是:
Warning: Cannot add header information - headers already sent...
header() 函数只能在 HTML 输出之前被调用,因此你需要检查 php 前面可能存在的空行,空格等等。
6. reload 的问题及其解决
我以前在写 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> 
?> 
假设我们用下面的连接使用这个程序:
... &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); 
he 
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> 
这样,原来的页面继续刷新也没有副作用了。
7. 巧用锁机制来提高应用性能
如果我们要紧急运行一个报表,那么,我们可以对表加写锁,防治别人读写,来提高对这个表的处理速度。
8. 用 mysql_unbuffered_query() 开发快速的脚本
这个函数能用来替换 mysql_query() 函数,主要的区别就是 mysql_unbuffered_query() 执行完查询后马上返回,不需要等待或者对数据库加锁。
但是返回的行数不能用mysql_num_rows() 函数来检查,因为输出的结果集大小未知。
您可能感兴趣的文章:
