← Back to Chapters

PHP PDO – Advanced Fetch Styles

? PHP PDO – Advanced Fetch Styles

? Quick Overview

PHP PDO provides multiple fetch styles that allow you to retrieve database records in different formats such as associative arrays, numeric arrays, objects, or mixed formats. Choosing the correct fetch style improves readability, memory usage, and development speed.

? Key Concepts

  • PDO fetch styles define how rows are returned
  • Each fetch mode suits a different programming need
  • Fetch styles can return arrays or objects
  • Proper usage improves clean data handling

? Syntax & Theory

The fetch() method accepts a fetch style constant that determines the structure of the returned row. Common styles include associative arrays, numeric arrays, and objects.

? Code Examples

? View Code Example
// Connect to database using PDO
$pdo = new PDO("mysql:host=localhost;dbname=testdb","root","");
$pdo->setAttribute(PDO::ATTR_ERRMODE,PDO::ERRMODE_EXCEPTION);

// Execute query
$stmt = $pdo->query("SELECT id,name,email FROM users");

// Fetch rows as associative arrays
while($row=$stmt->fetch(PDO::FETCH_ASSOC)){
print_r($row);
}

// Fetch rows as numeric arrays
while($row=$stmt->fetch(PDO::FETCH_NUM)){
print_r($row);
}

// Fetch rows as objects
while($row=$stmt->fetch(PDO::FETCH_OBJ)){
echo $row->name." - ".$row->email."
";
}

? Live Output / Explanation

FETCH_ASSOC returns column-name-based arrays.
FETCH_NUM returns index-based arrays.
FETCH_OBJ returns each row as an object with properties.

? Interactive Visualization

Each fetch style maps database rows differently, allowing flexibility between array-based and object-oriented programming approaches.

? Use Cases

  • Use FETCH_ASSOC for readable API responses
  • Use FETCH_OBJ in MVC and OOP-based applications
  • Use FETCH_NUM for faster indexed processing

✅ Tips & Best Practices

  • Prefer FETCH_ASSOC for clarity
  • Use FETCH_OBJ in object-oriented designs
  • Avoid unnecessary mixed fetch styles to save memory

? Try It Yourself

  • Fetch only one column using PDO::FETCH_COLUMN
  • Create key-value arrays using PDO::FETCH_KEY_PAIR
  • Compare output formats across fetch styles