DEV Community

Cover image for PHP 8.1: MySQLi: fetch_column function
Slava Rozhnev
Slava Rozhnev

Posted on

PHP 8.1: MySQLi: fetch_column function

Another suggestion made by Kamil Tekiela was included in the PHP 8.1 release.
Starting with this release, one more method has become available in the mysqli class - the fetch_column() method previously implemented in the PDO library.

Lets create simple table for our tests:

create table persons (
    id int primary key, 
    name varchar(64),
    age tinyint
);

insert into persons values (10, 'Alice', 18), (20, 'Bob', 22);

+====+=======+=====+
| id | name  | age |
+====+=======+=====+
| 10 | Alice | 18  |
| 20 | Bob   | 22  |
+----+-------+-----+

Enter fullscreen mode Exit fullscreen mode
$result = $mysqli->query("SELECT name FROM persons WHERE id = 10");

echo $result->fetch_column();
Enter fullscreen mode Exit fullscreen mode

You can test the above code here

If the query returns several columns, the fetch_column(n) function can return the value from the column whose number is passed as a function parameter (column numbering starts from 0).

$result = $mysqli->query("SELECT name, age FROM persons WHERE id = 10");

echo $result->fetch_column(1);
Enter fullscreen mode Exit fullscreen mode

Just like with other fetch_* methods this one will also move the internal result pointer to the next row when called. So you can not use fetch_column(i) for loop thought one record columns.
Next example explain this error:

<?php
$result = $mysqli->query("SELECT name, age FROM persons");

$name = $result->fetch_column(0);
$age  = $result->fetch_column(1);

// Returns Alice  name with Bob's age
printf("Name: %s, age: %d", $name, $age);
Enter fullscreen mode Exit fullscreen mode

Test PHP code online

Sentry image

Hands-on debugging session: instrument, monitor, and fix

Join Lazar for a hands-on session where you’ll build it, break it, debug it, and fix it. You’ll set up Sentry, track errors, use Session Replay and Tracing, and leverage some good ol’ AI to find and fix issues fast.

RSVP here →

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay