0
0
PhpHow-ToBeginner · 3 min read

How to Fetch Data as Object in PHP: Simple Guide

In PHP, you can fetch data as an object using PDOStatement::fetchObject() with PDO or mysqli_result::fetch_object() with MySQLi. These methods return each row as an object where columns become properties, making data access easy and intuitive.
📐

Syntax

Here are the basic ways to fetch data as an object in PHP:

  • PDO: Use $stmt->fetchObject() to get a single row as an object.
  • MySQLi: Use $result->fetch_object() to fetch a row as an object.

Each column in the database row becomes a property of the returned object.

php
<?php
// PDO syntax
$data = $stmt->fetchObject();

// MySQLi syntax
$row = $result->fetch_object();
💻

Example

This example shows how to connect to a MySQL database using PDO, run a query, and fetch the result as an object. You can access columns as object properties.

php
<?php
// Connect to MySQL using PDO
$pdo = new PDO('mysql:host=localhost;dbname=testdb', 'user', 'password');

// Prepare and execute query
$stmt = $pdo->query('SELECT id, name, email FROM users LIMIT 1');

// Fetch one row as object
$user = $stmt->fetchObject();

// Access properties
if ($user) {
    echo "ID: " . $user->id . "\n";
    echo "Name: " . $user->name . "\n";
    echo "Email: " . $user->email . "\n";
} else {
    echo "No user found.";
}
Output
ID: 1 Name: Alice Email: alice@example.com
⚠️

Common Pitfalls

Common mistakes when fetching data as objects include:

  • Not checking if the fetch returned false before accessing properties, which causes errors.
  • Using fetchObject() without executing the query first.
  • Confusing fetchObject() with fetch() which returns an array by default.

Always verify the query succeeded and the result is not false before using the object.

php
<?php
// Wrong: Not checking if fetchObject returned false
$user = $stmt->fetchObject();
echo $user->name; // Error if no data

// Right: Check before accessing
$user = $stmt->fetchObject();
if ($user !== false) {
    echo $user->name;
} else {
    echo "No data found.";
}
📊

Quick Reference

Summary of methods to fetch data as objects in PHP:

MethodDescriptionUsage Example
PDO::fetchObject()Fetches next row as an object$obj = $stmt->fetchObject();
MySQLi::fetch_object()Fetches next row as an object$obj = $result->fetch_object();

Key Takeaways

Use PDO's fetchObject() or MySQLi's fetch_object() to get query results as objects.
Always check if the fetch method returns false before accessing object properties.
Each database column becomes a property of the returned object for easy access.
PDO and MySQLi have similar but distinct methods for fetching objects.
Fetching as objects can make your code cleaner and more readable.