PHP PDO FetchAll() Tutorial

beginner
22 min

PHP PDO FetchAll() Tutorial

Welcome back to CodeYourCraft! Today, we're diving into the world of PHP and learning about the PDO fetchAll() method. 🎯

What is PDO?

PDO (PHP Data Objects) is a PHP extension for accessing databases. It provides a uniform PHP interface to various database systems like MySQL, PostgreSQL, and SQLite. PDO is an important part of PHP development as it simplifies the process of interacting with databases and helps in writing more secure code.

Introducing FetchAll()

The PDO FetchAll() method retrieves all the rows from a database result and returns them as an associative array or another suitable type depending on the mode you choose. Let's see some examples. πŸ“

Example 1: Basic Usage

php
<?php $pdo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password"); $stmt = $pdo->query("SELECT * FROM users"); $users = $stmt->fetchAll(); print_r($users); ?>

In this example, we're connecting to a MySQL database, executing a query to select all users, and using fetchAll() to get all the results as an associative array.

Example 2: FetchAll() with PDO::FETCH_OBJ

php
<?php $pdo = new PDO("mysql:host=localhost;dbname=testdb", "username", "password"); $stmt = $pdo->query("SELECT * FROM users"); $users = $stmt->fetchAll(PDO::FETCH_OBJ); foreach ($users as $user) { echo $user->name; } ?>

In this example, we're fetching all the results as objects, making it easier to access properties like $user->name.

Choosing the Right Fetch Mode

PDO offers several fetch modes to suit different needs. Here's a quick overview:

  • PDO::FETCH_ASSOC: Fetches rows as associative arrays with keys from column names.
  • PDO::FETCH_NUM: Fetches rows as numeric arrays indexed by the order of the columns.
  • PDO::FETCH_OBJ: Fetches rows as objects with properties named by the column names.
  • PDO::FETCH_OBJ_NUM: Fetches rows as objects with properties named by the order of the columns.

πŸ’‘ Pro Tip: Choose the fetch mode that best fits your needs and makes your code easier to read and maintain.

Wrapping Up

Now you know how to use the PHP PDO fetchAll() method to retrieve all the rows from a database result. In the next lessons, we'll dive deeper into PDO and explore more methods and best practices. πŸ“

Quick Quiz
Question 1 of 1

What does the PDO fetchAll() method do?