mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assoc 從結(jié)果集中取得一行作為關(guān)聯(lián)數(shù)組

警告

本擴(kuò)展自 PHP 5.5.0 起已廢棄,并在自 PHP 7.0.0 開始被移除。應(yīng)使用 MySQLiPDO_MySQL 擴(kuò)展來替換之。參見 MySQL:選擇 API 指南來獲取更多信息。用以替代本函數(shù)的有:

說明

mysql_fetch_assoc(resource $result): array

返回對應(yīng)結(jié)果集的關(guān)聯(lián)數(shù)組,并且繼續(xù)移動內(nèi)部數(shù)據(jù)指針。 mysql_fetch_assoc() 和用 mysql_fetch_array() 加上第二個可選參數(shù) MYSQL_ASSOC 完全相同。它僅僅返回關(guān)聯(lián)數(shù)組。

參數(shù)

result

resource 型的結(jié)果集。此結(jié)果集來自對 mysql_query() 的調(diào)用。

返回值

返回根據(jù)從結(jié)果集取得的行生成的關(guān)聯(lián)數(shù)組;如果沒有更多行則返回 false。

如果結(jié)果中的兩個或以上的列具有相同字段名,最后一列將優(yōu)先。要訪問同名的其它列,要么用 mysql_fetch_row() 來取得數(shù)字索引或給該列起個別名。 參見 mysql_fetch_array() 例子中有關(guān)別名說明。

范例

示例 #1 擴(kuò)展的 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);

?>

注釋

注意: 性能

必須指出一個要點(diǎn): mysql_fetch_assoc()mysql_fetch_row()不明顯 慢,而且還提供了更多有用的值。

注意: 此函數(shù)返回的字段名大小寫敏感。

注意: 此函數(shù)將 NULL 字段設(shè)置為 PHP null 值。

參見