(PHP 4 >= 4.0.3, PHP 5)
mysql_fetch_assoc — 從結果集中取得一行作為關聯數組
Warning本擴展自 PHP 5.5.0 起已廢棄,并在將來會被移除。應使用 MySQLi 或 PDO_MySQL 擴展來替換之。參見 MySQL:選擇 API 指南以及相關 FAQ 以獲取更多信息。用以替代本函數的有:
mysqli_fetch_assoc() PDOStatement::fetch(PDO::FETCH_ASSOC)說明
array mysql_fetch_assoc ( resource$result
)
返回對應結果集的關聯數組,并且繼續移動內部數據指針。 mysql_fetch_assoc() 和用 mysql_fetch_array() 加上第二個可選參數 MYSQL_ASSOC 完全相同。它僅僅返回關聯數組。
參數
result
resource 型的結果集。此結果集來自對 mysql_query() 的調用。
返回值
返回根據從結果集取得的行生成的關聯數組;如果沒有更多行則返回 FALSE
。
如果結果中的兩個或以上的列具有相同字段名,最后一列將優先。要訪問同名的其它列,要么用 mysql_fetch_row() 來取得數字索引或給該列起個別名。 參見 mysql_fetch_array() 例子中有關別名說明。
范例
Example #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);
?>
注釋
Note:
性能
必須指出一個要點: mysql_fetch_assoc() 比 mysql_fetch_row() 并不明顯 慢,而且還提供了更多有用的值。
Note: 此函數返回的字段名大小寫敏感。
Note: 此函數將 NULL 字段設置為 PHP NULL
值。
參見
mysql_fetch_row() - 從結果集中取得一行作為枚舉數組 mysql_fetch_array() - 從結果集中取得一行作為關聯數組,或數字數組,或二者兼有 mysql_data_seek() - 移動內部結果的指針 mysql_query() - 發送一條 MySQL 查詢 mysql_error() - 返回上一個 MySQL 操作產生的文本錯誤信息