萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 使用 mysql_fetch_assoc 將查詢結果存入關聯陣列

同樣注意:mysql_* 已移除,請改用 mysqli/PDO。mysql_fetch_assoc 返回關聯陣列(欄位名為鍵),比數值索引更易讀。

函數原型

mysql_fetch_assoc(resource $result): array|false

歷史範例

$result = mysql_query("SELECT ISBN, Title, Author FROM articles", $link);
while ($row = mysql_fetch_assoc($result)) {
    echo "ISBN = {$row['ISBN']}<br>\n";
    echo "Title = {$row['Title']}<br>\n";
    echo "Author = {$row['Author']}<br>\n";
}

現代 PDO 對應

$stmt = $pdo->query('SELECT ISBN, Title, Author FROM articles');
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
    echo "ISBN = {$row['ISBN']}<br>\n";
    // ...
}

mysqli 對應

$res = $mysqli->query('SELECT ISBN, Title, Author FROM articles');
while ($row = $res->fetch_assoc()) { /* ... */ }
copyright © 萬盛學電腦網 all rights reserved