0
0
PHPprogramming~30 mins

Fetch modes and styles in PHP - Mini Project: Build & Apply

Choose your learning style9 modes available
Fetch modes and styles
📖 Scenario: You are working with a database of books in a library. You want to fetch data from the database using different fetch modes to see how the data is returned in PHP.
🎯 Goal: Learn how to use different PDO fetch modes to retrieve data from a database and understand how the data structure changes with each mode.
📋 What You'll Learn
Create a PDO connection to an SQLite in-memory database
Create a table called books with columns id, title, and author
Insert three books into the books table
Fetch data using different PDO fetch modes: PDO::FETCH_ASSOC, PDO::FETCH_OBJ, and PDO::FETCH_NUM
Print the fetched results to see the differences
💡 Why This Matters
🌍 Real World
Fetching data from databases in different formats is common when building web applications or APIs. Knowing fetch modes helps you choose the best way to work with data.
💼 Career
Database interaction is a key skill for backend developers. Understanding PDO fetch modes is important for writing clean, efficient, and readable PHP code.
Progress0 / 4 steps
1
Create the database and books table
Create a PDO connection called $pdo to an SQLite in-memory database using new PDO("sqlite::memory:"). Then create a table called books with columns id (integer primary key), title (text), and author (text).
PHP
Need a hint?

Use new PDO("sqlite::memory:") to create the database connection. Use exec method to run the CREATE TABLE SQL.

2
Insert three books into the books table
Insert these three books into the books table using $pdo->exec(): (1, '1984', 'George Orwell'), (2, 'To Kill a Mockingbird', 'Harper Lee'), and (3, 'The Great Gatsby', 'F. Scott Fitzgerald').
PHP
Need a hint?

Use three separate exec calls to insert each book with exact values.

3
Fetch data using PDO::FETCH_ASSOC
Write code to prepare and execute a query to select all columns from books. Then fetch all results using fetchAll(PDO::FETCH_ASSOC) into a variable called $booksAssoc.
PHP
Need a hint?

Use prepare and execute methods on $pdo. Then use fetchAll(PDO::FETCH_ASSOC) to get associative arrays.

4
Fetch data using PDO::FETCH_OBJ and PDO::FETCH_NUM and print results
Fetch all books again using fetchAll(PDO::FETCH_OBJ) into $booksObj and using fetchAll(PDO::FETCH_NUM) into $booksNum. Then print $booksAssoc, $booksObj, and $booksNum using print_r() to see the differences.
PHP
Need a hint?

Remember to call execute() again before each fetchAll call because the statement cursor moves after fetching. Use print_r() to display the arrays and objects.