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);