PHP和MySQL開發的8個技巧

來源:互聯網
上載者:User

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

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.