(PHP 5 >= 5.1.0, PHP 7, PHP 8)
pg_fetch_all_columns — Fetches all rows in a particular result column as an array
pg_fetch_all_columns() returns an array that contains all rows (records) in a particular column of the PgSql\Result instance.
Note: This function sets NULL fields to the PHP
null
value.
result
An PgSql\Result instance, returned by pg_query() , pg_query_params() or pg_execute() (among others).
field
Column number. Defaults to the first column if not specified.
An array with all values in the result column.
Version | Description |
---|---|
8.1.0 |
The result parameter expects an PgSql\Result
instance now; previously, a resource was expected.
|
Example #1 pg_fetch_all_columns() example
<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occurred.\n";
exit;
}
$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
echo "An error occurred.\n";
exit;
}
// Get an array of all author names
$arr = pg_fetch_all_columns($result, 1);
var_dump($arr);
?>
Unfortunate that pg_fetch_all_columns() doesn't support fetching a column by its name -- if you want to do that, you'll need to use pg_field_num() as an intermediary:
For example:
<?php
if ($foo)
$cols = "email_address";
else
$cols = "last_name, middle_init";
$result = pg_query("Select first_name, $info, birthday from users_table");
// Problem -- does column #2 refer to the 'birthday' or 'middle_init' field?
$array = pg_fetch_all_columns($result, 2);
// Won't work, must use a column number instead of its name
$array = pg_fetch_all_columns($result, 'birthday');
// Works
$array = pg_fetch_all_columns($result, pg_field_num($result, 'birthday'));
?>
pg_fetch_all_columns() returns array (empty array) even if the result set in empty (while pg_fetch_all() returns FALSE when the result set is empty)
<?
$result = pg_query("
SELECT 'something'
WHERE 1 = 2
");
var_dump( pg_fetch_all($result) ); // boolean false
var_dump( pg_fetch_all_columns($result) ); // array(0){}
?>
php 4 equivalent:
<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "An error occured.\n";
exit;
}
$result = pg_query($conn, "SELECT title, name, address FROM authors");
if (!$result) {
echo "An error occured.\n";
exit;
}
// Get an array of all author names
$arr = array();
while ($line = pg_fetch_array($result)) {
array_push($arr, $line['name']);
}
var_dump($arr);
?>