注意: mysql_* 函數已於 PHP 7.0 移除,本文僅供舊版維護參考。新專案請改用 mysqli_fetch_assoc() 或 PDO::FETCH_ASSOC。
array mysql_fetch_assoc ( resource $result )
FALSE。<?php
$conn = mysql_connect('localhost', 'abc', '1234');
if (!$conn) die('連線失敗: ' . mysql_error());
if (!mysql_select_db('w3db', $conn)) die('選擇資料庫失敗');
$query = "SELECT ISBN, Title, Author FROM articles";
$result = mysql_query($query, $conn);
if (!$result) die('查詢失敗: ' . mysql_error());
$data = [];
while ($row = mysql_fetch_assoc($result)) {
$data[] = $row; // 將每列關聯陣列存入大陣列
}
// 釋放資源
mysql_free_result($result);
mysql_close($conn);
// 後續處理 $data
print_r($data);
?>
while ($row = mysql_fetch_assoc($result)) {
echo "ISBN = {$row['ISBN']}<br>";
echo "Title = {$row['Title']}<br>";
echo "Author = {$row['Author']}<br><br>";
}
<?php
$mysqli = new mysqli('localhost', 'abc', '1234', 'w3db');
$stmt = $mysqli->prepare("SELECT ISBN, Title, Author FROM articles");
$stmt->execute();
$result = $stmt->get_result();
$data = $result->fetch_all(MYSQLI_ASSOC); // 一次取得所有關聯陣列
$stmt->close();
$mysqli->close();
print_r($data);
?>
mysql_fetch_assoc 是以關聯陣列形式取得資料最直觀的函數,但請儘速遷移至 mysqli 或 PDO。善用 fetch_all() 可簡化迴圈程式碼。希望本文對您的 PHP 程式設計有所幫助。