fetchColumn

Summary: in this tutorial, you’ll learn how to use the fetchColumn() method to get a single column from the next row of a result set.

Introduction to fetchColumn() method

Sometimes, you want to get the value of a single column from the next row of a result set. In this case, you can use the fetchColumn() method of the PDOStatement object.

public PDOStatement::fetchColumn(int $column = 0): mixedCode language: PHP (php)

The fetchColumn() method accepts a column index that you want to retrieve.

The index of the first column is zero. The index of the second column is one, and so on. By default, the fetchColumn() method returns the value of the first row from the result set if you don’t explicitly pass a column index.

The fetchColumn() method returns the value of the column specified by the $column index. If the result set has no more rows, the method returns false.

Because of this, you should not use the fetchColumn() to retrieve values from the boolean columns. The reason is that you won’t be able to know whether false comes from the selected column or the result of no more rows.

A fetchColumn() method example

The following example uses the fetchColumn() method to get the name of the publisher with id 1:

<?php

$pdo = require 'connect.php';

$sql = 'SELECT name 
        FROM publishers 
        WHERE publisher_id = :publisher_id';

$statement = $pdo->prepare($sql);
$statement->execute(
    ['publisher_id' => 1]
);

$publisher_name = $pdo->fetchColumn();
echo $publisher_name;Code language: PHP (php)

How it works.

  • First, connect to the bookdb database using the connect.php script.
  • Next, construct an SQL SELECT statement to select a publisher by id.
  • Then, prepare the statement for execution by callig the prepare() method of the PDO object.
  • After that, execute the statement by passing the publisher id to 1.
  • Finally, get the name of the publisher from the selected row using the fetchColumn() method and display it.

If the publishers table doesn’t have a publisher with id 1, the $publisher_name will be false. And you won’t see anything in the output.

In practice, you will use the fetchColumn() to look up a value based on a unique id. For example, you can use the fetchColumn() method to check whether an email already exists in the users table:

SELECT id FROM users WHERE email := email;Code language: PHP (php)

If the result is false, it means that the email doesn’t exist.

Summary

  • Use fetchColumn() method of the PDOStatement object to get the value of a column from the next row in the result set.
Did you find this tutorial useful?