警告: mysql_* 函數已在 PHP 7.0 中移除。本文面向舊項目維護人員,新開發請直接使用 mysqli 或 PDO。
object mysql_fetch_object ( resource $result [, string $class_name = "stdClass" [, array $params ]] )
false。<?php
$link = mysql_connect('localhost', 'user', 'pass') or die('連接失敗');
mysql_select_db('test_db', $link);
$query = "SELECT isbn, title, author FROM books";
$result = mysql_query($query, $link);
while ($obj = mysql_fetch_object($result)) {
// 以對象屬性訪問
echo "ISBN: {$obj->isbn} | 書名: {$obj->title} | 作者: {$obj->author}<br>";
}
mysql_free_result($result);
?>
<?php
class Book {
public $isbn;
public $title;
public $author;
public function getCitation() {
return "《{$this->title}》 by {$this->author} (ISBN: {$this->isbn})";
}
}
while ($book = mysql_fetch_object($result, 'Book')) {
echo $book->getCitation() . "<br>";
}
?>
| 方式 | mysqli | PDO |
|---|---|---|
| 默認對象 (stdClass) | $result->fetch_object() | $stmt->fetch(PDO::FETCH_OBJ) |
| 自定義類映射 | $result->fetch_object('Book') | $stmt->fetch(PDO::FETCH_CLASS, 'Book') |
| 構造函數參數 | 不支持 | 支持 PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE |
<?php
$mysqli = new mysqli('localhost', 'user', 'pass', 'test_db');
$result = $mysqli->query("SELECT isbn, title, author FROM books");
while ($book = $result->fetch_object('Book')) {
echo $book->getCitation() . "<br>";
}
?>
<?php
$pdo = new PDO('mysql:host=localhost;dbname=test_db;charset=utf8', 'user', 'pass');
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$stmt = $pdo->query("SELECT isbn, title, author FROM books");
$stmt->setFetchMode(PDO::FETCH_CLASS, 'Book'); // 設置一次即可
while ($book = $stmt->fetch()) {
echo $book->getCitation() . "<br>";
}
?>
// 先調用構造函數,再綁定屬性(適合構造函數有必需參數的類) $stmt->setFetchMode(PDO::FETCH_CLASS | PDO::FETCH_PROPS_LATE, 'Book', [$arg1, $arg2]);
$result → 對象 $mysqli_result 或 PDOStatement。mysql_fetch_object($res, 'Class') → $res->fetch_object('Class') 或 $stmt->fetch(PDO::FETCH_CLASS, 'Class')。errno(mysqli)。