mysql_fetch_object() 將結果集的每一行轉為 **stdClass 物件**,欄位名成為物件屬性,適合偏好物件導向存取風格的開發者。
object mysql_fetch_object(resource $result, string $class_name = "stdClass", array $ctor_params = [])
stdClass。$ctor_params 傳入。<?php
$db = mysql_connect('localhost', 'abc', '1234');
mysql_select_db('w3db', $db);
mysql_query("SET NAMES utf8", $db);
$res = mysql_query("SELECT ISBN, Title, Author FROM articles", $db);
while ($obj = mysql_fetch_object($res)) {
echo "ISBN = {$obj->ISBN}<br>\n";
echo "Title = {$obj->Title}<br>\n";
echo "Author = {$obj->Author}<br>\n";
}
mysql_free_result($res);
mysql_close($db);
?>
class Article {
public $ISBN;
public $Title;
public $Author;
public function __construct() { /* 可做初始化 */ }
public function getCitation() {
return "《{$this->Title}》 by {$this->Author} (ISBN: {$this->ISBN})";
}
}
while ($article = mysql_fetch_object($res, 'Article')) {
echo $article->getCitation() . "<br>";
}
$pdo = new PDO("mysql:host=localhost;dbname=w3db;charset=utf8", 'abc', '1234');
$stmt = $pdo->query("SELECT ISBN, Title, Author FROM articles");
// stdClass
while ($obj = $stmt->fetch(PDO::FETCH_OBJ)) { echo $obj->Title; }
// 自訂類別
$stmt->setFetchMode(PDO::FETCH_CLASS, 'Article');
while ($article = $stmt->fetch()) { echo $article->getCitation(); }