說明
array
mysql_fetch_assoc ( resource result )
返回根據從結果集取得的行建立的關聯陣列,若果沒有更多行則返回 FALSE。
mysql_fetch_assoc() 和用
mysql_fetch_array() 加上第二個可選參數
MYSQL_ASSOC 完全相同。它僅僅返回關聯陣列。這也是
mysql_fetch_array()
起起始的工作模式。若果在關聯索引之外還需要數字索引,用
mysql_fetch_array()。
若果結果中的兩個或以上的列具有相同欄位名,最後一列將優先。要訪問同名的其它列,要麼用
mysql_fetch_row()
來取得數字索引或給該列起個別名。參見
mysql_fetch_array() 例子中有關別名說明。
有一點很重要必須指出,用
mysql_fetch_assoc()
並不明顯 比用
mysql_fetch_row()
慢,而且還提供了明顯更多的值。
例子 1. 增加的 mysql_fetch_assoc() 例子
<?php
$conn = mysql_connect("localhost", "mysql_user", "mysql_password");
if (!$conn) { echo "Unable to connect to DB: " . mysql_error(); exit; }
if (!mysql_select_db("mydbname")) { echo "Unable to select mydbname: " . mysql_error(); exit; }
$sql = "SELECT id as userid, fullname, userstatus FROM sometable WHERE userstatus = 1";
$result = mysql_query($sql);
if (!$result) { echo "Could not successfully run query ($sql) from DB: " . mysql_error(); exit; }
if (mysql_num_rows($result) == 0) { echo "No rows found, nothing to print so am exiting"; exit; }
// While a row of data exists, put that row in $row as an associative array // Note: If you're expecting just one row, no need to use a loop // Note: If you put extract($row); inside the following loop, you'll // then create $userid, $fullname, and $userstatus while ($row = mysql_fetch_assoc($result)) { echo $row["userid"]; echo $row["fullname"]; echo $row["userstatus"]; }
mysql_free_result($result);
?>
|
|
參見
mysql_fetch_row(),mysql_fetch_array(),mysql_query() 和
mysql_error()。