当前位置: 编程技术>php
本页文章导读:
▪一个PHP操作Access类(PHP+ODBC+Access)
代码如下:<?php -------------------------------------------------------------------- //FileName:class.php //Summary: Access数据库操作类 //Author: forest //CreateTime: 2006-8-10 //LastModifed: //copyright (c)2006 freeweb..........
▪一个用php实现的获取URL信息的类
获取URL信息的类 使用这个类,你能获得URL的如下信息: - Host - Path - Statuscode (eg. 404,200, ...) - HTTP Version - Server - Content Type - Date - The whole header string of the URL 代码如下.........
▪PHP 和 MySQL 开发的 8 个技巧
1. PHP 中数组的使用 在操作数据库时,使用关联数组(associatively-indexed arrays)十分有帮助,下面我们看一个基本的数字格式的数组遍历: <?php $temp[0] = "richmond"; $temp[1] = "t.........
[1]一个PHP操作Access类(PHP+ODBC+Access)
来源: 互联网 发布时间: 2013-11-30
代码如下:
<?php
--------------------------------------------------------------------
//FileName:class.php
//Summary: Access数据库操作类
//Author: forest
//CreateTime: 2006-8-10
//LastModifed:
//copyright (c)2006 freeweb.nyist.net/~chairy [email]chaizuxue@163.com[/email]
// 使用范例:
//$databasepath="database.mdb";
//$dbusername="";
//$dbpassword="";
//include_once("class.php");
//$access=new Access($databasepath,$dbusername,$dbpassword);
--------------------------------------------------------------------
class Access
{
var $databasepath,$constr,$dbusername,$dbpassword,$link;
function Access($databasepath,$dbusername,$dbpassword)
{
$this->databasepath=$databasepath;
$this->username=$dbusername;
$this->password=$dbpassword;
$this->connect();
}
function connect()
{
$this->constr="DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=" . realpath($this->databasepath);
$this->link=odbc_connect($this->constr,$this->username,$this->password,SQL_CUR_USE_ODBC);
return $this->link;
//if($this->link) echo "恭喜你,数据库连接成功!";
//else echo "数据库连接失败!";
}
function query($sql)
{
return @odbc_exec($this->link,$sql);
}
function first_array($sql)
{
return odbc_fetch_array($this->query($sql));
}
function fetch_row($query)
{
return odbc_fetch_row($query);
}
function total_num($sql)//取得记录总数
{
return odbc_num_rows($this->query($sql));
}
function close()//关闭数据库连接函数
{
odbc_close($this->link);
}
function insert($table,$field)//插入记录函数
{
$temp=explode(',',$field);
$ins='';
for ($i=0;$i<count($temp);$i++)
{
$ins.="'".$_POST[$temp[$i]]."',";
}
$ins=substr($ins,0,-1);
$sql="INSERT INTO ".$table." (".$field.") VALUES (".$ins.")";
$this->query($sql);
}
function getinfo($table,$field,$id,$colnum)//取得当条记录详细信息
{
$sql="SELECT * FROM ".$table." WHERE ".$field."=".$id."";
$query=$this->query($sql);
if($this->fetch_row($query))
{
for ($i=1;$i<$colnum;$i++)
{
$info[$i]=odbc_result($query,$i);
}
}
return $info;
}
function getlist($table,$field,$colnum,$condition,$sort="ORDER BY id DESC")//取得记录列表
{
$sql="SELECT * FROM ".$table." ".$condition." ".$sort;
$query=$this->query($sql);
$i=0;
while ($this->fetch_row($query))
{
$recordlist[$i]=getinfo($table,$field,odbc_result($query,1),$colnum);
$i++;
}
return $recordlist;
}
function getfieldlist($table,$field,$fieldnum,$condition="",$sort="")//取得记录列表
{
$sql="SELECT ".$field." FROM ".$table." ".$condition." ".$sort;
$query=$this->query($sql);
$i=0;
while ($this->fetch_row($query))
{
for ($j=0;$j<$fieldnum;$j++)
{
$info[$j]=odbc_result($query,$j+1);
}
$rdlist[$i]=$info;
$i++;
}
return $rdlist;
}
function updateinfo($table,$field,$id,$set)//更新记录
{
$sql="UPDATE ".$table." SET ".$set." WHERE ".$field."=".$id;
$this->query($sql);
}
function deleteinfo($table,$field,$id)//删除记录
{
$sql="DELETE FROM ".$table." WHERE ".$field."=".$id;
$this->query($sql);
}
function deleterecord($table,$condition)//删除指定条件的记录
{
$sql="DELETE FROM ".$table." WHERE ".$condition;
$this->query($sql);
}
function getcondrecord($table,$condition="")// 取得指定条件的记录数
{
$sql="SELECT COUNT(*) AS num FROM ".$table." ".$condition;
$query=$this->query($sql);
$this->fetch_row($query);
$num=odbc_result($query,1);
return $num;
}
}
?>
[2]一个用php实现的获取URL信息的类
来源: 互联网 发布时间: 2013-11-30
获取URL信息的类
使用这个类,你能获得URL的如下信息:
- Host
- Path
- Statuscode (eg. 404,200, ...)
- HTTP Version
- Server
- Content Type
- Date
- The whole header string of the URL
<?
/**
* Class for getting information about URL's
* @author Sven Wagener <[email]sven.wagener@intertribe.de[/email]>
* @copyright Intertribe limited
* @PHP中文社区收集整理 [url]www.phpNet.cn[/url]
* @include Funktion:_include_
*/
class url{
var $url="";
var $url_host;
var $url_path;
var $file="";
var $code="";
var $code_desc="";
var $http_version=""; // Variable for HTTP version
var $header_stream;
var $header_array;
var $timeout="1";
/**
* Constructor of class url
* @param string $url the complete url
* @desc Constructor of class url
*/
function url(/blog_article/$url/index.html){
$this->url=$url;
$url_array=parse_url(/blog_article/$this->url/index.html);
$this->url_host=$url_array['host'];
$this->url_path=$url_array['path'];
if($this->url_path==""){
$this->url_path="/";
}
$this->refresh_headerinfo();
}
/**
* Returns the whole url
* @return string $url the whole url
* @desc Returns the whole url
*/
function get_url(){
return $this->url;
}
/**
* Returns the host of the url
* @return string $url_host the host of the url
* @desc Returns the host of the url
*/
function get_url_host(){
return $this->url_host;
}
/**
* Returns the path of the url
* @return string $url_path the path of the url
* @desc Returns the path of the url
*/
function get_url_path(){
return $this->url_path;
}
/**
* Returns the status code of the url
* @return string $status_code the status code
* @desc Returns the status code of the url
*/
function get_statuscode(){
return $this->code;
}
/**
* Returns the status code description of the url
* @return string $status_code_desc the status code description
* @desc Returns the status code description of the url
*/
function get_statuscode_desc(){
return $this->code_desc;
}
/**
* Returns the http version of the url by the returned headers of the server
* @return string $http_version the http version
* @desc Returns the http version of the url by the returned headers of the server
*/
function get_info_http_version(){
return $this->http_version;
}
/**
* Returns the server type of the url's host by the returned headers of the server
* @return string header_array['Server'] the server type
* @desc Returns the server type of the url's host by the returned headers of the server
*/
function get_info_server(){
return $this->header_array['Server'];
}
/**
* Returns the date of the url's host by the returned headers of the server
* @return string $header_array['Date'] the date
* @desc Returns the date of the url's host by the returned headers of the server
*/
function get_info_date(){
return $this->header_array['Date'];
}
/*
function get_info_content_length(){
return $this->header_array['Content-Length'];
}
*/
/**
* Returns the content type by the returned headers of the server
* @return string header_array['Content-Type'] the content type
* @desc Returns the content type by the returned headers of the server
*/
function get_info_content_type(){
return $this->header_array['Content-Type'];
}
/**
* Returns the content of the url without the headers
* @return string $content the content
* @desc Returns the content of the url without the headers
*/
function get_content(){
// Get a web page into a string
$string = implode ('', file ($this->url));
return $string;
}
/**
* Returns the whole header of url without content
* @return string $header the header
* @desc Returns the whole header of url without content
*/
function get_header_stream(){
return $this->header_stream;
}
/**
* Returns the whole headers of the url in an array
* @return array $header_array the headers in an array
* @desc Returns the whole headers of the url in an array
*/
function get_headers(){
return $this->header_array;
}
/**
* Refreshes the header information
* @desc Refreshes the header information
*/
function refresh_headerinfo(){
// Open socket for connection via port 80 to put headers
$fp = fsockopen ($this->url_host, 80, $errno, $errstr, 30);
if (!$fp) {
// echo "$errstr ($errno)";
if($errno==0){
$errstr="Server Not Found";
}
$this->code=$errno;
$this->code_desc=$errstr;
} else {
$put_string="GET ".$this->url_path." HTTP/1.0rnHost: ".$this->url_host."rnrn";
fputs ($fp, $put_string);
@socket_set_timeout($fp,$this->timeout);
$stream="";
$this->header_array="";
$header_end=false;
// Getting header string and creating header array
$i=0;
while (!feof($fp) && !$header_end) {
$line=fgets($fp,128);
if(strlen($line)==2){
$header_end=true;
}else{
if($i==0){
$line1=$line;
}
$stream.=$line;
$splitted_line=split(":",$line);
$this->header_array[$splitted_line[0]]=$splitted_line[1];
$i++;
}
}
fclose ($fp);
$this->header_stream=$stream;
$splitted_stream=split(" ",$line1);
// Getting status code and description of the URL
$this->code=$splitted_stream[1];
$this->code_desc=$splitted_stream[2];
if(count($splitted_stream)>3){
for($i=3;$i<count($splitted_stream);$i++){
$this->code_desc.=" ".$splitted_stream[$i];
}
}
// Cleaning up for n and r
$this->code_desc=preg_replace("[\n]","",$this->code_desc);
$this->code_desc=preg_replace("[\r]","",$this->code_desc);
// Getting Http Version
$http_array=split("/",$splitted_stream[0]);
$this->http_version=$http_array[1];
}
}
/**
* Sets the timeout for getting header data from server
* @param int $seconds time for timeout in seconds
* @desc Sets the timeout for getting header data from server
*/
function set_timeout($seconds){
$this->timeout=$seconds;
}
}
?>
<?php
include("url.class.php");
$url=new url("/blog_article/[url]http_/www.phpNet.cn/[/url]/index.html");
echo $url->get_header_stream();
$headers=$url->get_headers();
echo $headers['Server'];
echo $url->get_content();
echo "URL: <b>".$url->get_url()."</b><br>n";
echo "URL Host: ".$url->get_url_host()."<br>n";
echo "URL Path: ".$url->get_url_path()."<br>n<br>n";
echo "Statuscode: ".$url->get_statuscode()."<br>n";
echo "Statuscode description: ".$url->get_statuscode_desc()."<br>n";
echo "HTTP Version: ".$url->get_info_http_version()."<br>n";
echo "Server: ".$url->get_info_server()."<br>n";
echo "Content Type: ".$url->get_info_content_type()."<br>n";
echo "Date: ".$url->get_info_date()."<br>n<br>n";
echo "WHOLE HEADERS:<br>n";
echo $url->get_header_stream();
?>
使用这个类,你能获得URL的如下信息:
- Host
- Path
- Statuscode (eg. 404,200, ...)
- HTTP Version
- Server
- Content Type
- Date
- The whole header string of the URL
代码如下:
<?
/**
* Class for getting information about URL's
* @author Sven Wagener <[email]sven.wagener@intertribe.de[/email]>
* @copyright Intertribe limited
* @PHP中文社区收集整理 [url]www.phpNet.cn[/url]
* @include Funktion:_include_
*/
class url{
var $url="";
var $url_host;
var $url_path;
var $file="";
var $code="";
var $code_desc="";
var $http_version=""; // Variable for HTTP version
var $header_stream;
var $header_array;
var $timeout="1";
/**
* Constructor of class url
* @param string $url the complete url
* @desc Constructor of class url
*/
function url(/blog_article/$url/index.html){
$this->url=$url;
$url_array=parse_url(/blog_article/$this->url/index.html);
$this->url_host=$url_array['host'];
$this->url_path=$url_array['path'];
if($this->url_path==""){
$this->url_path="/";
}
$this->refresh_headerinfo();
}
/**
* Returns the whole url
* @return string $url the whole url
* @desc Returns the whole url
*/
function get_url(){
return $this->url;
}
/**
* Returns the host of the url
* @return string $url_host the host of the url
* @desc Returns the host of the url
*/
function get_url_host(){
return $this->url_host;
}
/**
* Returns the path of the url
* @return string $url_path the path of the url
* @desc Returns the path of the url
*/
function get_url_path(){
return $this->url_path;
}
/**
* Returns the status code of the url
* @return string $status_code the status code
* @desc Returns the status code of the url
*/
function get_statuscode(){
return $this->code;
}
/**
* Returns the status code description of the url
* @return string $status_code_desc the status code description
* @desc Returns the status code description of the url
*/
function get_statuscode_desc(){
return $this->code_desc;
}
/**
* Returns the http version of the url by the returned headers of the server
* @return string $http_version the http version
* @desc Returns the http version of the url by the returned headers of the server
*/
function get_info_http_version(){
return $this->http_version;
}
/**
* Returns the server type of the url's host by the returned headers of the server
* @return string header_array['Server'] the server type
* @desc Returns the server type of the url's host by the returned headers of the server
*/
function get_info_server(){
return $this->header_array['Server'];
}
/**
* Returns the date of the url's host by the returned headers of the server
* @return string $header_array['Date'] the date
* @desc Returns the date of the url's host by the returned headers of the server
*/
function get_info_date(){
return $this->header_array['Date'];
}
/*
function get_info_content_length(){
return $this->header_array['Content-Length'];
}
*/
/**
* Returns the content type by the returned headers of the server
* @return string header_array['Content-Type'] the content type
* @desc Returns the content type by the returned headers of the server
*/
function get_info_content_type(){
return $this->header_array['Content-Type'];
}
/**
* Returns the content of the url without the headers
* @return string $content the content
* @desc Returns the content of the url without the headers
*/
function get_content(){
// Get a web page into a string
$string = implode ('', file ($this->url));
return $string;
}
/**
* Returns the whole header of url without content
* @return string $header the header
* @desc Returns the whole header of url without content
*/
function get_header_stream(){
return $this->header_stream;
}
/**
* Returns the whole headers of the url in an array
* @return array $header_array the headers in an array
* @desc Returns the whole headers of the url in an array
*/
function get_headers(){
return $this->header_array;
}
/**
* Refreshes the header information
* @desc Refreshes the header information
*/
function refresh_headerinfo(){
// Open socket for connection via port 80 to put headers
$fp = fsockopen ($this->url_host, 80, $errno, $errstr, 30);
if (!$fp) {
// echo "$errstr ($errno)";
if($errno==0){
$errstr="Server Not Found";
}
$this->code=$errno;
$this->code_desc=$errstr;
} else {
$put_string="GET ".$this->url_path." HTTP/1.0rnHost: ".$this->url_host."rnrn";
fputs ($fp, $put_string);
@socket_set_timeout($fp,$this->timeout);
$stream="";
$this->header_array="";
$header_end=false;
// Getting header string and creating header array
$i=0;
while (!feof($fp) && !$header_end) {
$line=fgets($fp,128);
if(strlen($line)==2){
$header_end=true;
}else{
if($i==0){
$line1=$line;
}
$stream.=$line;
$splitted_line=split(":",$line);
$this->header_array[$splitted_line[0]]=$splitted_line[1];
$i++;
}
}
fclose ($fp);
$this->header_stream=$stream;
$splitted_stream=split(" ",$line1);
// Getting status code and description of the URL
$this->code=$splitted_stream[1];
$this->code_desc=$splitted_stream[2];
if(count($splitted_stream)>3){
for($i=3;$i<count($splitted_stream);$i++){
$this->code_desc.=" ".$splitted_stream[$i];
}
}
// Cleaning up for n and r
$this->code_desc=preg_replace("[\n]","",$this->code_desc);
$this->code_desc=preg_replace("[\r]","",$this->code_desc);
// Getting Http Version
$http_array=split("/",$splitted_stream[0]);
$this->http_version=$http_array[1];
}
}
/**
* Sets the timeout for getting header data from server
* @param int $seconds time for timeout in seconds
* @desc Sets the timeout for getting header data from server
*/
function set_timeout($seconds){
$this->timeout=$seconds;
}
}
?>
代码如下:
<?php
include("url.class.php");
$url=new url("/blog_article/[url]http_/www.phpNet.cn/[/url]/index.html");
echo $url->get_header_stream();
$headers=$url->get_headers();
echo $headers['Server'];
echo $url->get_content();
echo "URL: <b>".$url->get_url()."</b><br>n";
echo "URL Host: ".$url->get_url_host()."<br>n";
echo "URL Path: ".$url->get_url_path()."<br>n<br>n";
echo "Statuscode: ".$url->get_statuscode()."<br>n";
echo "Statuscode description: ".$url->get_statuscode_desc()."<br>n";
echo "HTTP Version: ".$url->get_info_http_version()."<br>n";
echo "Server: ".$url->get_info_server()."<br>n";
echo "Content Type: ".$url->get_info_content_type()."<br>n";
echo "Date: ".$url->get_info_date()."<br>n<br>n";
echo "WHOLE HEADERS:<br>n";
echo $url->get_header_stream();
?>
[3]PHP 和 MySQL 开发的 8 个技巧
来源: 互联网 发布时间: 2013-11-30
1. PHP 中数组的使用
在操作数据库时,使用关联数组(associatively-indexed arrays)十分有帮助,下面我们看一个基本的数字格式的数组遍历:
<?php
$temp[0] = "richmond";
$temp[1] = "tigers";
$temp[2] = "premiers";
for($x=0;$x<count($temp);$x++)
{
echo $temp[$x];
echo " ";
}
?>
然而另外一种更加节省代码的方式是:
<?php
$temp = array("richmond", "tigers", "premiers");
foreach ($temp as $element)
echo "$element ";
?>
foreach 还能输出文字下标:
<?php
$temp = array("club" => "richmond",
"nickname" =>"tigers",
"aim" => "premiers");
foreach ($temp as $key => $value)
echo "$key : $value ";
?>
PHP 手册中描述了大约 50 个用于处理数组的函数。
2. 在 PHP 字符串中加入变量
这个很简单的:
<?php
$temp = "hello"
echo "$temp world";
?>
但是需要说明的是,尽管下面的例子没有错误:
<?php
$temp = array("one" => 1, "two" => 2);
// 输出:: The first element is 1
echo "The first element is $temp[one].";
?>
但是如果后面那个 echo 语句没有双引号引起来的话,就要报错,因此建议使用花括号:
<?php
$temp = array("one" => 1, "two" => 2);
echo "The first element is {$temp["one"]}.";
?>
3. 采用关联数组存取查询结果
看下面的例子:
<?php
$connection = mysql_connect("localhost", "albert", "shhh");
mysql_select_db("winestore", $connection);
$result = mysql_query("SELECT cust_id, surname,
firstname FROM customer", $connection);
while ($row = mysql_fetch_array($result))
{
echo "ID:\t{$row["cust_id"]}\n";
echo "Surname\t{$row["surname"]}\n";
echo "First name:\t{$row["firstname"]}\n\n";
}
?>
函数 mysql_fetch_array() 把查询结果的一行放入数组,可以同时用两种方式引用,例如 cust_id 可以同时用下面两种方式:$row["cust_id"] 或者$row[0] 。显然,前者的可读性要比后者好多了。
在多表连查中,如果两个列名字一样,最好用别名分开:
SELECT winery.name AS wname,
region.name AS rname,
FROM winery, region
WHERE winery.region_id = region.region_id;
列名的引用为:$row["wname"] 和 $row["rname"]。
在指定表名和列名的情况下,只引用列名:
SELECT winery.region_id
FROM winery
列名的引用为: $row["region_id"]。
聚集函数的引用就是引用名:
SELECT count(*)
FROM customer;
列名的引用为: $row["count(*)"]。
4. 注意常见的 PHP bug
常见的 PHP 纠错问题是:
No page rendered by the Web browser when much more is expected
A pop-up dialog stating that the "Document Contains No Data"
A partial page when more is expected
出现这些情况的大多数原因并不在于脚本的逻辑,而是 HTML 中存在的 bug 或者脚本生成的 HTML 的 bug 。例如缺少类似 </table>, </form>, </frame> 之类的关闭 Tag,页面就不能刷新。解决这个问题的办法就是,查看 HTML 的源代码。
对于复杂的,不能查到原因的页面,可以通过 W3C 的页面校验程序 http://validator.w3.org/ 来分析。
如果没有定义变量,或者变量定义错误也会让程序变得古怪。例如下面的死循环:
<?php
for($counter=0; $counter<10; $Counter++)
myFunction();
?>
变量 $Counter 在增加,而 $counter 永远小于 10。这类错误一般都能通过设置较高的错误报告级别来找到:
<?php
error_reporting(E_ALL);
for($counter=0; $counter<10; $Counter++)
myFunction();
?>
5. 采用 header() 函数处理单部件查询
在很多 Web 数据库应用中,一些功能往往让用户点击一个连接后,继续停留在当前页面,这样的工作我叫它“单部件查询”。
下面是一个叫做 calling.php 的脚本:
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<title>Calling page example</title>
</head>
<body>
<a href="/blog_article/action.html">Click here!</a>
</body>
</html>
当用户点击上面的连接时,就去调用 action.php。下面是 action.php 的源码:
<?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>
?>
假设我们用下面的连接使用这个程序:
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>
这样,原来的页面继续刷新也没有副作用了。
7. 巧用锁机制来提高应用性能
如果我们要紧急运行一个报表,那么,我们可以对表加写锁,防治别人读写,来提高对这个表的处理速度。
8. 用 mysql_unbuffered_query() 开发快速的脚本
这个函数能用来替换 mysql_query() 函数,主要的区别就是 mysql_unbuffered_query() 执行完查询后马上返回,不需要等待或者对数据库加锁。
但是返回的行数不能用mysql_num_rows() 函数来检查,因为输出的结果集大小未知。
在操作数据库时,使用关联数组(associatively-indexed arrays)十分有帮助,下面我们看一个基本的数字格式的数组遍历:
<?php
$temp[0] = "richmond";
$temp[1] = "tigers";
$temp[2] = "premiers";
for($x=0;$x<count($temp);$x++)
{
echo $temp[$x];
echo " ";
}
?>
然而另外一种更加节省代码的方式是:
<?php
$temp = array("richmond", "tigers", "premiers");
foreach ($temp as $element)
echo "$element ";
?>
foreach 还能输出文字下标:
<?php
$temp = array("club" => "richmond",
"nickname" =>"tigers",
"aim" => "premiers");
foreach ($temp as $key => $value)
echo "$key : $value ";
?>
PHP 手册中描述了大约 50 个用于处理数组的函数。
2. 在 PHP 字符串中加入变量
这个很简单的:
<?php
$temp = "hello"
echo "$temp world";
?>
但是需要说明的是,尽管下面的例子没有错误:
<?php
$temp = array("one" => 1, "two" => 2);
// 输出:: The first element is 1
echo "The first element is $temp[one].";
?>
但是如果后面那个 echo 语句没有双引号引起来的话,就要报错,因此建议使用花括号:
<?php
$temp = array("one" => 1, "two" => 2);
echo "The first element is {$temp["one"]}.";
?>
3. 采用关联数组存取查询结果
看下面的例子:
<?php
$connection = mysql_connect("localhost", "albert", "shhh");
mysql_select_db("winestore", $connection);
$result = mysql_query("SELECT cust_id, surname,
firstname FROM customer", $connection);
while ($row = mysql_fetch_array($result))
{
echo "ID:\t{$row["cust_id"]}\n";
echo "Surname\t{$row["surname"]}\n";
echo "First name:\t{$row["firstname"]}\n\n";
}
?>
函数 mysql_fetch_array() 把查询结果的一行放入数组,可以同时用两种方式引用,例如 cust_id 可以同时用下面两种方式:$row["cust_id"] 或者$row[0] 。显然,前者的可读性要比后者好多了。
在多表连查中,如果两个列名字一样,最好用别名分开:
SELECT winery.name AS wname,
region.name AS rname,
FROM winery, region
WHERE winery.region_id = region.region_id;
列名的引用为:$row["wname"] 和 $row["rname"]。
在指定表名和列名的情况下,只引用列名:
SELECT winery.region_id
FROM winery
列名的引用为: $row["region_id"]。
聚集函数的引用就是引用名:
SELECT count(*)
FROM customer;
列名的引用为: $row["count(*)"]。
4. 注意常见的 PHP bug
常见的 PHP 纠错问题是:
No page rendered by the Web browser when much more is expected
A pop-up dialog stating that the "Document Contains No Data"
A partial page when more is expected
出现这些情况的大多数原因并不在于脚本的逻辑,而是 HTML 中存在的 bug 或者脚本生成的 HTML 的 bug 。例如缺少类似 </table>, </form>, </frame> 之类的关闭 Tag,页面就不能刷新。解决这个问题的办法就是,查看 HTML 的源代码。
对于复杂的,不能查到原因的页面,可以通过 W3C 的页面校验程序 http://validator.w3.org/ 来分析。
如果没有定义变量,或者变量定义错误也会让程序变得古怪。例如下面的死循环:
<?php
for($counter=0; $counter<10; $Counter++)
myFunction();
?>
变量 $Counter 在增加,而 $counter 永远小于 10。这类错误一般都能通过设置较高的错误报告级别来找到:
<?php
error_reporting(E_ALL);
for($counter=0; $counter<10; $Counter++)
myFunction();
?>
5. 采用 header() 函数处理单部件查询
在很多 Web 数据库应用中,一些功能往往让用户点击一个连接后,继续停留在当前页面,这样的工作我叫它“单部件查询”。
下面是一个叫做 calling.php 的脚本:
<!DOCTYPE HTML PUBLIC
"-//W3C//DTD HTML 4.0 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd" >
<html>
<head>
<title>Calling page example</title>
</head>
<body>
<a href="/blog_article/action.html">Click here!</a>
</body>
</html>
当用户点击上面的连接时,就去调用 action.php。下面是 action.php 的源码:
<?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>
?>
假设我们用下面的连接使用这个程序:
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>
这样,原来的页面继续刷新也没有副作用了。
7. 巧用锁机制来提高应用性能
如果我们要紧急运行一个报表,那么,我们可以对表加写锁,防治别人读写,来提高对这个表的处理速度。
8. 用 mysql_unbuffered_query() 开发快速的脚本
这个函数能用来替换 mysql_query() 函数,主要的区别就是 mysql_unbuffered_query() 执行完查询后马上返回,不需要等待或者对数据库加锁。
但是返回的行数不能用mysql_num_rows() 函数来检查,因为输出的结果集大小未知。
最新技术文章: