Retrieving a Single Field from a Table in PDO in PHP
Besides the fetch method, there is
a special method fetchColumn,
which allows you to get the value of a single column.
Let's see what is meant.
First, let's prepare and execute
a query. We will specify that we want
to select only the
name field:
<?php
$res = $pdo->prepare('SELECT name FROM users');
$res->execute();
?>
Let's get the results using the
fetch method:
<?php
while ($col = $res->fetch()) {
var_dump($col);
}
?>
As a result, in each iteration we will see an array consisting of one element - the user's name:
['name1']
['name2']
['name3']
Now let's apply fetchColumn:
<?php
while ($col = $res->fetchColumn()) {
var_dump($col);
}
?>
As a result, in each iteration we will see the string with the user's name itself, not an array:
'name1'
'name2'
'name3'
Get the values of all user ages.