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 |
+----+-------+-----+
$result = $mysqli->query("SELECT name FROM persons WHERE id = 10");
echo $result->fetch_column();
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);
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);
Top comments (0)