2024 年 PHP Conference Japan

mysql_fetch_assoc

(PHP 4 >= 4.0.3, PHP 5)

mysql_fetch_assoc將結果列擷取為關聯式陣列

警告

此擴充功能已於 PHP 5.5.0 中棄用,並在 PHP 7.0.0 中移除。建議改用 MySQLiPDO_MySQL 擴充功能。另請參閱 MySQL:選擇 API 指南。此函式的替代方案包括:

說明

mysql_fetch_assoc(資源 $result): 陣列

傳回與擷取的資料列相對應的關聯式陣列,並將內部資料指標向前移動。 mysql_fetch_assoc() 等同於以 MYSQL_ASSOC 作為第二個選用參數呼叫 mysql_fetch_array()。它只會傳回關聯式陣列。

參數

result

正在評估的結果 資源。此結果來自對 mysql_query() 的呼叫。

傳回值

傳回與擷取的資料列相對應的字串關聯式陣列,如果沒有更多資料列,則傳回 false

如果結果的兩個或多個欄位具有相同的欄位名稱,則最後一個欄位將優先。要存取同名的其他欄位,您需要使用 mysql_fetch_row() 以數值索引存取結果,或新增別名。請參閱 mysql_fetch_array() 說明中關於別名的範例。

範例

範例 #1 mysql_fetch_assoc() 的擴展範例

<?php

$conn
= mysql_connect("localhost", "mysql_user", "mysql_password");

if (!
$conn) {
echo
"無法連線到資料庫: " . mysql_error();
exit;
}

if (!
mysql_select_db("mydbname")) {
echo
"無法選擇 mydbname 資料庫: " . mysql_error();
exit;
}

$sql = "SELECT id as userid, fullname, userstatus
FROM sometable
WHERE userstatus = 1"
;

$result = mysql_query($sql);

if (!
$result) {
echo
"無法成功執行查詢 ($sql): " . mysql_error();
exit;
}

if (
mysql_num_rows($result) == 0) {
echo
"找不到任何資料列,沒有任何內容可以印出,因此將會結束程式";
exit;
}

// 當存在資料列時,將該列以關聯陣列的形式放入 $row 中
// 注意:如果您只預期有一列資料,則不需要使用迴圈
// 注意:如果您在以下迴圈中使用 extract($row);,您將
// 建立 $userid、$fullname 和 $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 值。

另請參閱

新增筆記

使用者貢獻的筆記 6 則筆記

marREtijn dot posthMOuma at hoVEme dot nl
21 年前
看來結果陣列中不能有 table.field 這種名稱的欄位。
如果您使用多表查詢且結果為空,請使用別名。

$res=mysql_query("SELECT user.ID AS uID, order.ID AS oID FROM user, order WHERE ( order.userid=uID )";
while ($row=mysql_fetch_assoc($res)) {
echo "<p>使用者 ID: $row['uID'],訂單 ID: $row['oID']</p>";
}
joe at kybert dot com
20 年前
值得指出的是,在收集當前列的資料後,內部列指標會遞增。

這表示多次呼叫會迭代列資料,因此您在呼叫之間不需要 mysql_data_seek(..)。

這在 mysql_fetch_row() 的文件中已說明,但這裡沒有!?
Typer85 at gmail dot com
18 年前
請注意,傳遞給此函式的資源結果可以被視為以傳址方式傳遞,因為資源只是一個指向記憶體位置的指標。

因此,在將指標重置回起始位置之前,您無法在同一個腳本中迴圈處理資源結果兩次。

例如

----------------
<?php

// 假設我們已經查詢了我們的資料庫。

// 迴圈處理結果集。

while( $queryContent = mysql_fetch_row( $queryResult ) {

// 顯示。

echo $queryContent[ 0 ];
}

// 我們已經迴圈處理了資源結果,所以
// 指標不再指向任何列。

// 如果我們決定再次迴圈處理相同的資源結果
// 該函式將永遠返回 false,因為它
// 會假設沒有更多列。

// 因此,如果在之前的程式碼段之後執行以下程式碼
// 將無法正常運作。

while( $queryContent = mysql_fetch_row( $queryResult ) {

// 顯示。

echo $queryContent[ 0 ];
}

// 因為 $queryContent 現在等於 FALSE,所以迴圈
// 將不會被進入。

?>
----------------

唯一的解決方案是在第二個程式碼段之前重置指標,使其再次指向第一列,因此現在完整的程式碼如下所示:

----------------
<?php

// 假設我們已經查詢了資料庫。

// 迴圈處理結果集。

while( $queryContent = mysql_fetch_row( $queryResult ) {

// 顯示。

echo $queryContent[ 0 ];
}

// 重置指標。

mysql_data_seek( $queryResult );

// 再次迴圈。

while( $queryContent = mysql_fetch_row( $queryResult ) {

// 顯示。

echo $queryContent[ 0 ];
}

?>
----------------

當然,您必須進行額外的檢查,以確保結果集中的列數不為 0,否則 mysql_data_seek 本身將返回 false 並引發錯誤。

另請注意,這適用於所有擷取結果集的函式,包括 mysql_fetch_row、mysql_fetch_assoc 和 mysql_fetch_array。
george at georgefisher dot com
15 年前
感謝 R. Bradley 提供的 implode 想法。以下修正了一些錯誤,並包含了 quote_smart 功能(並且已經過測試)。

<?php
function mysql_insert_assoc ($my_table, $my_array) {

//
// Insert values into a MySQL database
// Includes quote_smart code to foil SQL Injection
//
// A call to this function of:
//
// $val1 = "foobar";
// $val2 = 495;
// mysql_insert_assoc("tablename", array(col1=>$val1, col2=>$val2, col3=>"val3", col4=>720, col5=>834.987));
//
// Sends the following query:
// INSERT INTO 'tablename' (col1, col2, col3, col4, col5) values ('foobar', 495, 'val3', 720, 834.987)
//

global $db_link;

// Find all the keys (column names) from the array $my_array
$columns = array_keys($my_array);

// Find all the values from the array $my_array
$values = array_values($my_array);

// quote_smart the values
$values_number = count($values);
for (
$i = 0; $i < $values_number; $i++)
{
$value = $values[$i];
if (
get_magic_quotes_gpc()) { $value = stripslashes($value); }
if (!
is_numeric($value)) { $value = "'" . mysql_real_escape_string($value, $db_link) . "'"; }
$values[$i] = $value;
}

// Compose the query
$sql = "INSERT INTO $my_table ";

// create comma-separated string of column names, enclosed in parentheses
$sql .= "(" . implode(", ", $columns) . ")";
$sql .= " values ";

// create comma-separated string of values, enclosed in parentheses
$sql .= "(" . implode(", ", $values) . ")";

$result = @mysql_query ($sql) OR die ("<br />\n<span style=\"color:red\">Query: $sql UNsuccessful :</span> " . mysql_error() . "\n<br />");

return (
$result) ? true : false;
}
?>
R. Bradley
18 年前
回應 Sergiu 的函式 - 使用 implode() 會讓事情變得更容易... 如下所示

<?php
函式 mysql_insert_assoc ($my_table, $my_array) {

// 從 $my_array 陣列中找出所有的鍵 (欄位名稱)
$columns = array_keys($my_array);

// 從陣列中找出所有的值
$values = array_values($my_array);

// 組合查詢語句
$sql = "insert into `$my_table` ";
// 將欄位名稱串接起來,在每個欄位名稱之間插入 "\", \"" (最後一個之後不加)
// 同時加上括號引號
$sql .= "(\"" . implode("\", \"", $column_names) . "\")";
$sql .= " values ";
// 值也一樣
$sql .= "(" . implode(", ", $values) . ")";

$result = mysql_query($sql);

if (
$result)
{
echo
"已成功新增資料列";
return
true;
}
else
{
echo (
"新增資料列失敗<br>錯誤訊息:" . mysql_error());
return
false;
}
}
?>

因此,呼叫這個函式的寫法如下:
mysql_insert_assoc("tablename", array("col1"=>"val1", "col2"=>"val2"));

會將以下 SQL 查詢語句傳送至 MySQL:
INSERT INTO `tablename` ("col1", "col2") VALUES ("val1", "val2")
benlanc at ster dot me dot uk
19 年前
這或許不需多說,但將 list() 與 mysql_fetch_assoc() 搭配使用是無效的 - 應該使用 mysql_fetch_row()。

<?php
$sql
= "SELECT `id`,`field`,`value` FROM `table`";
$result = mysql_query($sql);

// 這會導致 rowID、fieldName、myValue 的值為空
list($rowID,$fieldName,$myValue) = mysql_fetch_assoc($result);

// 這才是您想要的:
list($rowID,$fieldName,$myValue) = mysql_fetch_row($result);
?>
To Top