All Rows from Result in PDO in PHP
You can immediately get an array of all
rows from the query result.
This is done using the fetchAll method.
Let's look at the different modes of operation
of this method.
All examples will be for the test table.
Getting a Simple Array
Let's apply the fetchAll method
to get a simple data array.
To do this, we leave the method parameters
empty:
<?php
$res = $pdo->query('SELECT * FROM users');
$row = $res->fetchAll();
var_dump($row);
?>
Code execution result:
[
[
'id' => 1,
'name' => 'name1',
'age' => 21,
'salary' => 500,
],
[
'id' => 2,
'name' => 'name2',
'age' => 22,
'salary' => 600,
],
[
'id' => 3,
'name' => 'name3',
'age' => 23,
'salary' => 600,
],
[
'id' => 4,
'name' => 'name4',
'age' => 24,
'salary' => 700,
],
[
'id' => 5,
'name' => 'name5',
'age' => 25,
'salary' => 800,
],
]
Getting a Single Column
Let's get only one column
from the table. To do this, pass
the FETCH_COLUMN parameter
to the fetchAll method:
<?php
$res = $pdo->query('SELECT name FROM users');
$row = $res->fetchAll(PDO::FETCH_COLUMN);
var_dump($row);
?>
Code execution result:
[
'name1',
'name2',
'name3',
'name4',
'name5',
]
Getting a Key-Value Pair
Let's get the data in the form of
a key-value pair, where the key will be the id,
and the value will be the user's name. To do this, pass the
FETCH_KEY_PAIR mode as a parameter
to the fetchAll method:
<?php
$res = $pdo->query('SELECT id, name FROM users');
$row = $res->fetchAll(PDO::FETCH_KEY_PAIR);
var_dump($row);
?>
Code execution result:
[
1 => 'name1',
2 => 'name2',
3 => 'name3',
4 => 'name4',
5 => 'name5',
]
Getting Records with a Unique Field
You can make it so that a unique field (generally
this is id) becomes the key for each
subarray:
<?php
$res = $pdo->query('SELECT * FROM users');
$row = $res->fetchAll(PDO::FETCH_UNIQUE);
var_dump($row);
?>
Code execution result:
[
1 => [
'id' => 1,
'name' => 'name1',
'age' => 21,
'salary' => 500,
],
2 => [
'id' => 2,
'name' => 'name2',
'age' => 22,
'salary' => 600,
],
3 => [
'id' => 3,
'name' => 'name3',
'age' => 23,
'salary' => 600,
],
4 => [
'id' => 4,
'name' => 'name4',
'age' => 24,
'salary' => 700,
],
5 => [
'id' => 5,
'name' => 'name5',
'age' => 25,
'salary' => 800,
],
]
Practical Tasks
Display all users
from the users table,
using the method described in the lesson.
Display one row of data
from the users table.
Display the name and age of users as a key-value pair.