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.
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.
// 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."
";
}
FETCH_ASSOC returns column-name-based arrays.
FETCH_NUM returns index-based arrays.
FETCH_OBJ returns each row as an object with properties.
Each fetch style maps database rows differently, allowing flexibility between array-based and object-oriented programming approaches.
FETCH_ASSOC for readable API responsesFETCH_OBJ in MVC and OOP-based applicationsFETCH_NUM for faster indexed processing