0
0
PHPprogramming~5 mins

Fetching results (fetch, fetchAll) in PHP

Choose your learning style9 modes available
Introduction

Fetching results lets you get data from a database after running a query. It helps you use that data in your PHP program.

You want to show a list of users from a database on a webpage.
You need to get details of one product to display on a product page.
You want to process all rows returned by a database query.
You want to get just one row from a query result quickly.
Syntax
PHP
$stmt = $pdo->query('SELECT * FROM table');
$row = $stmt->fetch();
$allRows = $stmt->fetchAll();

fetch() gets one row at a time from the result.

fetchAll() gets all rows at once as an array.

Examples
This gets the first user name from the users table.
PHP
$stmt = $pdo->query('SELECT name FROM users');
$row = $stmt->fetch();
echo $row['name'];
This gets all user names and prints each on a new line.
PHP
$stmt = $pdo->query('SELECT name FROM users');
$allUsers = $stmt->fetchAll();
foreach ($allUsers as $user) {
    echo $user['name'] . "\n";
}
Sample Program

This program creates a small users table, inserts three names, then fetches the first user with fetch(). Next, it fetches all remaining users with fetchAll() and prints their names.

PHP
<?php
// Connect to SQLite in memory for example
$pdo = new PDO('sqlite::memory:');
// Create a sample table
$pdo->exec("CREATE TABLE users (id INTEGER PRIMARY KEY, name TEXT)");
// Insert sample data
$pdo->exec("INSERT INTO users (name) VALUES ('Alice'), ('Bob'), ('Charlie')");

// Query the table
$stmt = $pdo->query('SELECT * FROM users');

// Fetch one row
$firstUser = $stmt->fetch();
echo "First user: " . $firstUser['name'] . "\n";

// Fetch all remaining rows
$allUsers = $stmt->fetchAll();
echo "All users after first:\n";
foreach ($allUsers as $user) {
    echo $user['name'] . "\n";
}
OutputSuccess
Important Notes

After calling fetch(), the internal pointer moves forward, so fetchAll() gets the remaining rows.

If you want all rows at once, just use fetchAll() without calling fetch() first.

Always check if the query succeeded before fetching results to avoid errors.

Summary

fetch() gets one row from the query result.

fetchAll() gets all rows as an array.

Use these to get data from your database queries and work with it in PHP.