Current Location: Home> Latest Articles> Create RESTful API using the custom class of PDOStatement::fetchObject

Create RESTful API using the custom class of PDOStatement::fetchObject

gitbox 2025-05-29

In modern PHP development, PDO (PHP Data Objects) provides a lightweight and efficient database access interface. The PDOStatement::fetchObject function can help us instantiate the database query results directly into objects. Combined with custom classes, you can quickly build a well-structured RESTful API. This article will explain in detail how to achieve this using PDOStatement::fetchObject .

When developing a RESTful API, processing database query results often requires a clear and maintainable way. PDOStatement::fetchObject allows us to convert query results directly into instances of custom classes, which not only simplifies the code, but also improves the readability and maintainability of the overall architecture.

Below we use a complete example to build a simple user (User) API.

Step 1: Create database and tables

Suppose we have a user table with the following structure:

 CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    name VARCHAR(100) NOT NULL,
    email VARCHAR(100) NOT NULL
);

And insert some test data:

 INSERT INTO users (name, email) VALUES 
('Alice', '[email protected]'),
('Bob', '[email protected]');

Step 2: Define user class (User.php)

This class will be used to map database query results.

 class User
{
    public int $id;
    public string $name;
    public string $email;

    public function toArray(): array
    {
        return [
            'id'    => $this->id,
            'name'  => $this->name,
            'email' => $this->email,
        ];
    }
}

The toArray method facilitates us to convert objects into array format so that we can return JSON in the API.

Step 3: Establish a database connection (db.php)

 <?php
function getPDO(): PDO
{
    $dsn = 'mysql:host=localhost;dbname=api_example;charset=utf8mb4';
    $username = 'root';
    $password = '';

    return new PDO($dsn, $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
    ]);
}
?>

Step 4: Write API entry file (api.php)

 <?php
require 'db.php';
require 'User.php';

// Set the response header
header('Content-Type: application/json');

$pdo = getPDO();

// Get usersID,If so
$id = $_GET['id'] ?? null;

if ($id) {
    // Get a single user
    $stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
    $stmt->execute(['id' => $id]);
    $user = $stmt->fetchObject('User');

    if ($user) {
        echo json_encode($user->toArray());
    } else {
        http_response_code(404);
        echo json_encode(['error' => 'User not found']);
    }
} else {
    // Get all users
    $stmt = $pdo->query('SELECT * FROM users');
    $users = [];
    while ($user = $stmt->fetchObject('User')) {
        $users[] = $user->toArray();
    }
    echo json_encode($users);
}
?>

Step 5: Test the API

Start your local server, such as using a built-in PHP server:

 php -S localhost:8000

Then visit the following address to test:

In real deployment, you can replace the server address with your own domain name, for example:

 https://api.gitbox.net/api.php?id=1

summary

With PDOStatement::fetchObject , we can map database records into custom objects very elegantly, thus simplifying the development process of the RESTful API. With object-oriented design, it not only makes the project more modular, but also makes subsequent expansions (such as adding verification and serialization rules) easier.