首页 > 开发 > PHP > 正文

PHP 和 MySQL 开发的 8 个技巧

2024-05-04 22:14:01
字体:
来源:转载
供稿:网友
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";  
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表