LAMP 架构的网站,我以前注重的多是安装/配置方面的,讲述开发的相对较少,因为自己从事开发也少。本文的原文当然也来自: Published on The O'Reilly Network (http://www.oreillynet.com/) http://www.oreillynet.com/pub/a/onlamp/2002/04/04/webdb.html 看了以后,颇有启发,以前开发中遇到的一些问题,迎刃而解。所以翻译出来和大家共享。 1. PHP 中数组的使用 在操作数据库时,使用关联数组(associatively-indexed arrays)十分有帮助,下面我们看一个基本的数字格式的数组遍历: $temp[0] = "richmond"; $temp[1] = "tigers"; $temp[2] = "premiers"; for($x=0;$x { echo $temp[$x]; echo " "; } ?> 然而另外一种更加节省代码的方式是: $temp = array("richmond", "tigers", "premiers"); foreach ($temp as $element) echo "$element "; ?> foreach 还能输出文字下标: $temp = array("club" => "richmond", "nickname" =>"tigers", "aim" => "premiers"); foreach ($temp as $key => $value) echo "$key : $value "; ?> PHP 手册中描述了大约 50 个用于处理数组的函数。 2. 在 PHP 字符串中加入变量 这个很简单的: $temp = "hello" echo "$temp world"; ?> 但是需要说明的是,尽管下面的例子没有错误: $temp = array("one" => 1, "two" => 2); // 输出:: The first element is 1 echo "The first element is $temp[one]."; ?> 但是如果后面那个 echo 语句没有双引号引起来的话,就要报错,因此建议使用花括号: $temp = array("one" => 1, "two" => 2); echo "The first element is {$temp["one"]}."; ?> 3. 采用关联数组存取查询结果 看下面的例子:
$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; |