PHP PDO fetch() Tutorial 🎯

beginner
23 min

PHP PDO fetch() Tutorial 🎯

Welcome to our PHP PDO fetch() tutorial! This lesson is designed for both beginners and intermediates, so let's get started.

What is PDO? πŸ“

PDO (PHP Data Objects) is a PHP extension that provides a uniform PHP interface for accessing various database systems. It helps in writing database-independent code.

Why Use PDO? πŸ’‘

  1. PDO provides a standardized way to interact with different databases, making your code more portable.
  2. It offers better security as it allows prepared statements, reducing the risk of SQL injection attacks.
  3. PDO supports transactions, which is useful for maintaining database consistency.

Introduction to fetch() πŸ“

fetch() is a method used to fetch a single row from a database. It's part of the PDOStatement interface, and it returns an associative array representing the row.

Basic Example 🎯

Let's create a simple example to understand the fetch() method better.

php
<?php try { $pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password"); $stmt = $pdo->query("SELECT id, name FROM users"); while ($row = $stmt->fetch()) { echo $row['id'] . ": " . $row['name'] . "\n"; } } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } ?>

In this example, we're connecting to a MySQL database, executing a SELECT query, and fetching each row until there are no more rows left.

Advanced Example 🎯

Now, let's consider a more practical scenario where we fetch data using a prepared statement. This helps to prevent SQL injection attacks.

php
<?php try { $pdo = new PDO("mysql:host=localhost;dbname=myDB", "username", "password"); $stmt = $pdo->prepare("SELECT id, name FROM users WHERE name = ?"); $stmt->execute(array('John')); $row = $stmt->fetch(); echo $row['id'] . ": " . $row['name'] . "\n"; } catch (PDOException $e) { echo "Error: " . $e->getMessage(); } ?>

In this example, we're preparing a statement with a placeholder (?), which will be replaced with the actual value ('John') when we execute the query.

Fetch Modes πŸ“

fetch() supports different modes to control how the data is returned. Here are some common modes:

  • fetch(PDO::FETCH_ASSOC): Returns an associative array.
  • fetch(PDO::FETCH_NUM): Returns a numeric array.
  • fetch(PDO::FETCH_BOTH): Returns an associative array with numeric keys.

Quiz 🎯

Quick Quiz
Question 1 of 1

What does the `fetch()` method in PHP PDO do?

That's it for this PHP PDO fetch() tutorial! We hope you found it helpful and engaging. As always, if you have any questions or need further clarification, feel free to ask. Happy coding! πŸ’‘