首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 綜合知識

PHP 使用 mysql_fetch_object 取得物件導向的查詢結果集

     編輯:PHP 綜合知識

前言

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)

$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(); }

注意事項

  • mysql_* 已移除**,請改用 PDO 或 MySQLi。
  • 物件屬性名**區分大小寫**,需與資料庫欄位名完全一致。
  • 自訂類別建構子在 **fetch 之後** 呼叫(PDO 行為),屬性已填入。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved