0
0
PHPprogramming~30 mins

Fetching results (fetch, fetchAll) in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Fetching results using fetch and fetchAll in PHP
📖 Scenario: You are building a simple PHP script to get user data from a database. You want to learn how to fetch one row at a time and how to fetch all rows at once.
🎯 Goal: Learn how to use fetch() and fetchAll() methods to get data from a database query result.
📋 What You'll Learn
Create a PDO connection to an SQLite in-memory database
Create a table called users with columns id, name, and email
Insert three users with exact data
Use fetch() to get one user row
Use fetchAll() to get all user rows
Print the fetched results
💡 Why This Matters
🌍 Real World
Fetching data from databases is a common task in web development. Knowing how to get one row or all rows helps you display data efficiently.
💼 Career
Many jobs require working with databases and PHP. Understanding fetch methods is essential for backend development and data handling.
Progress0 / 4 steps
1
Create the database and insert users
Create a PDO connection called $pdo to an SQLite in-memory database. Then create a table called users with columns id (integer primary key), name (text), and email (text). Insert these three users exactly: (1, 'Alice', 'alice@example.com'), (2, 'Bob', 'bob@example.com'), and (3, 'Charlie', 'charlie@example.com').
PHP
Need a hint?

Use new PDO('sqlite::memory:') to create the database. Use exec() to run SQL commands.

2
Prepare a SELECT query
Create a variable called $stmt that prepares the SQL query SELECT * FROM users using the $pdo connection.
PHP
Need a hint?

Use $pdo->prepare() with the exact SQL string.

3
Fetch one user row using fetch()
Execute the prepared statement $stmt. Then create a variable called $oneUser that fetches one row using fetch() with PDO::FETCH_ASSOC to get an associative array.
PHP
Need a hint?

Call execute() before fetching. Use fetch(PDO::FETCH_ASSOC) to get one row as an associative array.

4
Fetch all user rows using fetchAll() and print results
Create a variable called $allUsers that fetches all rows using fetchAll() with PDO::FETCH_ASSOC. Then print $oneUser and $allUsers using print_r().
PHP
Need a hint?

Use fetchAll(PDO::FETCH_ASSOC) to get all rows as an array of associative arrays. Use print_r() to display arrays.