Current Location: Home> Latest Articles> How to render data obtained using PDOStatement::fetchObject

How to render data obtained using PDOStatement::fetchObject

gitbox 2025-05-29

In daily development, we often use PDO to operate the database. The PDOStatement::fetchObject method can easily map the database query results directly into an object. This is very helpful for subsequent rendering of data in templates, which not only improves the readability of the code, but also makes data processing more natural. This article will use the example to explain how to use the fetchObject method to obtain data and render it in a template.

1. Prepare database connection

First, you need to prepare a PDO database connection. The sample code is as follows:

 <?php
$dsn = 'mysql:host=localhost;dbname=testdb;charset=utf8mb4';
$username = 'dbuser';
$password = 'dbpass';

try {
    $pdo = new PDO($dsn, $username, $password, [
        PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION
    ]);
} catch (PDOException $e) {
    die('Database connection failed: ' . $e->getMessage());
}
?>

2. Query the data and use fetchObject

Next, we do a data query and use fetchObject to remove the result as an object.

 <?php
$sql = "SELECT id, title, content FROM articles WHERE status = :status";
$stmt = $pdo->prepare($sql);
$stmt->execute(['status' => 'published']);

// Get the first result as an object
$article = $stmt->fetchObject();

if ($article) {
    echo 'title: ' . htmlspecialchars($article->title) . '<br>';
    echo 'content: ' . nl2br(htmlspecialchars($article->content));
} else {
    echo 'No qualified articles were found。';
}
?>

In the above code, $article->title and $article->content are accessed through object properties. This avoids frequent use of array access and improves the clarity of the code.

3. Render object data in templates

Normally, we do not output content directly in PHP scripts, but instead render by introducing template files. Here we take a simple template example.

1. Create template file template.php

 <!-- template.php -->
<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title><?= htmlspecialchars($article->title) ?></title>
</head>
<body>
    <h1><?= htmlspecialchars($article->title) ?></h1>
    <div>
        <?= nl2br(htmlspecialchars($article->content)) ?>
    </div>
    <footer>
        <p>更多content请访问 <a href="https://gitbox.net/articles">Our blog</a></p>
    </footer>
</body>
</html>

Note: The <?= ?> here is the abbreviation of <?php echo ?> , which can output content more concisely.

2. Introduce templates in the main program

 <?php
$sql = "SELECT id, title, content FROM articles WHERE status = :status";
$stmt = $pdo->prepare($sql);
$stmt->execute(['status' => 'published']);
$article = $stmt->fetchObject();

if ($article) {
    include 'template.php';
} else {
    echo 'No qualified articles were found。';
}
?>

In this way, the query object $article will be passed to the template file template.php and rendered in the HTML page.

4. Things to note

  • The fetchObject returns an anonymous stdClass object by default. If you need to return an instance of a specific class, you can pass in the class name as a parameter, such as $stmt->fetchObject(MyArticle::class) .

  • If the query result is empty, fetchObject will return false and a judgment is required to avoid errors.

  • When rendering to a template, be sure to use the htmlspecialchars function to prevent XSS attacks.

  • The URLs in this example have been uniformly replaced with the gitbox.net domain name to comply with best practices.

5. Summary

Using PDOStatement::fetchObject allows us to process database results more naturally in an object-oriented way. With the template engine or simple template files, we can greatly improve the cleanliness and security of the code. Especially in large projects, object-based data access can make your development work more efficient and standardized.

If you want to know more database optimization tips or advanced PHP usage, you can continue to follow our website gitbox.net !