mysql_fetch_assoc
(PHP 4 >= 4.0.3, PHP 5)
mysql_fetch_assoc — 從結果集中取得一行作為關聯陣列
警告
本擴充套件自 PHP 5.5.0 起已廢棄,並在自 PHP 7.0.0 開始被移除。應使用 MySQLi 或 PDO_MySQL 擴充套件來替換之。參見 MySQL:選擇 API 指南來獲取更多資訊。用以替代本函式的有:
說明
mysql_fetch_assoc(resource
$result
): array返回對應結果集的關聯陣列,並且繼續移動內部數據指針。 mysql_fetch_assoc() 和用 mysql_fetch_array() 加上第二個可選參數 MYSQL_ASSOC 完全相同。它僅僅返回關聯陣列。
返回值
返回根據從結果集取得的行產生的關聯陣列;如果沒有更多行則返回 false
。
如果結果中的兩個或以上的列具有相同欄位名,最後一列將優先。要訪問同名的其它列,要麼用 mysql_fetch_row() 來取得數字索引或給該列起個別名。 參見 mysql_fetch_array() 例子中有關別名說明。
範例
示例 #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_assoc() 比 mysql_fetch_row() 並不明顯 慢,而且還提供了更多有用的值。
注意: 此函式返回的欄位名大小寫敏感。
注意: 此函式將 NULL 欄位設定為 PHP
null
值。
參見
- mysql_fetch_row() - 從結果集中取得一行作為列舉陣列
- mysql_fetch_array() - 從結果集中取得一行作為關聯陣列
- mysql_data_seek() - 移動內部結果的指針
- mysql_query() - 發送一條 MySQL 查詢
- mysql_error() - 返回上一個 MySQL 操作產生的文字錯誤資訊