PHP 8.1 – MySQLi: fetch_column()

PHP 8.1 – MySQLi: fetch_column()

database icon with tick icon

New function was added to retrieve first or any other column from the result set to MySQLi object. This follows the fetchColumn() method from PDO and behaves in the same manner.

This change borrows the idea from PDO to add another method to mysqli_result class. The method would be called fetch_column to keep with the existing mysqli naming convention.

//old way
$result = $mysqli->query('SELECT username FROM users WHERE id = 123');
echo $result->fetch_row()[0] ?? false;

//new equivalent method
$result = $mysqli->query('SELECT username FROM users WHERE id = 123');
echo $result->fetch_column();

There will be only two differences from PDO: the name of the method, and the fact that MySQL doesn’t have boolean types thus this method can never return a boolean. However, the method can still return false, which indicates that no row could be fetched from the result.

More about PHP 8.1

Read about all PHP 8.1 features and changes in here.

Leave a Comment