如何正確理解PHP獲取顯示數(shù)據(jù)庫數(shù)據(jù)函數(shù)
在運用PHP語言對數(shù)據(jù)庫進(jìn)行操作的時候,我們將會用到mysql_X這一函數(shù)庫。下面我們將為大家詳細(xì)介紹有關(guān)PHP獲取顯示數(shù)據(jù)庫數(shù)據(jù)函數(shù)的函數(shù)。#t#
PHP獲取顯示數(shù)據(jù)庫數(shù)據(jù)函數(shù)之 mysql_result()
mixed mysql_result(resource result_set, int row [,mixed field])
從result_set 的指定row 中獲取一個field 的數(shù)據(jù). 簡單但是效率低.
舉例:
- $link1 = @mysql_connect("server1",
"webuser", "password") - or die("Could not connect
to mysql server!"); - @mysql_select_db("company")
or die("Could not select database!"); - $query = "select id, name
from product order by name"; - $result = mysql_query($query);
- $id = mysql_result($result, 0, "id");
- $name = mysql_result($result, 0, "name");
- mysql_close();
注意,上述代碼只是輸出結(jié)果集中的***條數(shù)據(jù)的字段值,如果要輸出所有記錄,需要循環(huán)處理.
- for ($i = 0; $i <= mysql_num_rows($result); $i++)
- {
- $id = mysql_result($result, 0, "id");
- $name = mysql_result($result, 0, "name");
- echo "Product: $name ($id)";
- }
注意,如果查詢字段名是別名,則mysql_result中就使用別名.
PHP獲取顯示數(shù)據(jù)庫數(shù)據(jù)函數(shù)之mysql_fetch_row()
array mysql_fetch_row(resource result_set)
從result_set中獲取整行,把數(shù)據(jù)放入數(shù)組中.
舉例(注意和list 的巧妙配合):
- $query = "select id,
name from product order by name";- $result = mysql_query($query);
- while(list($id, $name)
= mysql_fetch_row($result)) {- echo "Product: $name ($id)";
- }
PHP獲取顯示數(shù)據(jù)庫數(shù)據(jù)函數(shù)之mysql_fetch_array()
array mysql_fetch_array(resource result_set [,int result_type])
mysql_fetch_row()的增強(qiáng)版.
將result_set的每一行獲取為一個關(guān)聯(lián)數(shù)組或/和數(shù)值索引數(shù)組.
默認(rèn)獲取兩種數(shù)組,result_type可以設(shè)置:
MYSQL_ASSOC:返回關(guān)聯(lián)數(shù)組,字段名=>字段值
MYSQL_NUM:返回數(shù)值索引數(shù)組.
MYSQL_BOTH:獲取兩種數(shù)組.因此每個字段可以按索引偏移引用,也可以按字段名引用.
舉例:
- $query = "select id,
name from product order by name";- $result = mysql_query($query);
- while($row = mysql_fetch_array
($result, MYSQL_BOTH)) {- $name = $row['name'];
- //或者 $name = $row[1];
- $name = $row['id'];
- //或者 $name = $row[0];
- echo "Product: $name ($id)";
- }
PHP獲取顯示數(shù)據(jù)庫數(shù)據(jù)函數(shù)之mysql_fetch_assoc()
array mysql_fetch_assoc(resource result_set)
相當(dāng)于 mysql_fetch_array($result, MYSQL_ASSOC)
PHP獲取顯示數(shù)據(jù)庫數(shù)據(jù)函數(shù)之mysql_fetch_object()
object mysql_fetch_object(resource result_set)
和mysql_fetch_array()功能一樣,不過返回的不是數(shù)組,而是一個對象.
舉例:
- $query = "select id, name
from product order by name";- $result = mysql_query($query);
- while($row = mysql_fetch_object
($result)) {- $name = $row->name;
- $name = $row->id;
- echo "Product: $name ($id)";
- }
以上這些函數(shù)就是PHP獲取顯示數(shù)據(jù)庫數(shù)據(jù)函數(shù)的全部總結(jié)。