pg_fetch_array

(PHP 4, PHP 5, PHP 7, PHP 8)

pg_fetch_array Lit une ligne de résultat PostgreSQL dans un tableau

Description

pg_fetch_array(PgSql\Result $result, ?int $row = null, int $mode = PGSQL_BOTH): array|false

pg_fetch_array() retourne un tableau qui contient la ligne demandée.

pg_fetch_array() est une version évoluée de pg_fetch_row(). En plus de proposer un tableau à indice numérique, elle peut aussi enregistrer les données dans un tableau associatif, en utilisant les noms des champs comme clés. Ces deux fonctions utilisent le tableau associatif par défaut.

Note: Cette fonction définit les champs NULL à la valeur PHP null.

pg_fetch_array() n'est pas significativement plus lente que pg_fetch_row() et elle apporte un confort d'utilisation appréciable.

Liste de paramètres

result

Une instance PgSql\Result, retourné par pg_query(), pg_query_params(), ou pg_execute() (entre autres).

row

Numéro de la ligne à récupérer. Les lignes sont numérotées en commençant à 0. Si l'argument est omis ou s'il vaut null, la ligne suivante est récupérée.

mode

Un paramètre optionnel qui contrôle la façon dont le array retourné est indexé. mode est une constante qui peut prendre les valeurs suivantes : PGSQL_ASSOC, PGSQL_NUM et PGSQL_BOTH. En utilisant PGSQL_NUM, la fonction retournera un tableau avec des indices numériques, en utilisant PGSQL_ASSOC, elle retournera seulement des indices associatifs tandis que PGSQL_BOTH retournera à la fois des indices numériques et associatifs.

Valeurs de retour

Un tableau à indice numérique (commençant à 0), associatif (indexé avec le nom des champs) ou les deux. Chaque valeur dans le tableau est représentée comme une chaîne (chaîne de caractères). Les valeurs null de la base de données sont retournées null.

false est retournée si row excède le nombre de lignes dans le jeu de résultats, n'a plus de ligne disponible ou tout autre erreur. Tenter de récupérer le résultat d'une requête autre que SELECT retournera aussi false.

Historique

Version Description
8.1.0 Le paramètre result attend désormais une instance de PgSql\Result ; auparavant, une ressource était attendu.

Exemples

Exemple #1 Exemple avec pg_fetch_array()

<?php

$conn
= pg_pconnect ("dbname=publisher");
if (!
$conn) {
echo
"Erreur de connexion.\n";
exit;
}

$result = pg_query ($conn, "SELECT auteur, email FROM auteurs");
if (!
$result) {
echo
"Erreur durant la requête.\n";
exit;
}

$arr = pg_fetch_array ($result, 0, PGSQL_NUM);
echo
$arr[0] . " <- Ligne 1 Auteurs\n";
echo
$arr[1] . " <- Ligne 1 E-mail\n";

// Le paramètre row est optionnel ; NULL peut être passé à la place,
// pour passer un mode. Les appels successifs à pg_fetch_array
// retournera la ligne suivante.
$arr = pg_fetch_array($result, NULL, PGSQL_ASSOC);
echo
$arr["auteur"] . " <- Ligne 2 Auteur\n";
echo
$arr["email"] . " <- Ligne 2 E-mail\n";

$arr = pg_fetch_array($result);
echo
$arr["auteur"] . " <- Ligne 3 Auteur\n";
echo
$arr[1] . " <- Ligne 3 E-mail\n";

?>

Voir aussi

add a note add a note

User Contributed Notes 12 notes

up
3
mkb at ele dot uri dot edu
23 years ago
The column names if you use PGSQL_ASSOC or PGSQL_BOTH are always in lowercase, no matter what the name is in the database or in the query.
up
3
jesse at sokieserv dot dhs dot org
22 years ago
As of PHP 4.1.0, you can now use code such as the following to iterate through a result set:

$conn = pg_connect("host=localhost dbname=whatever");
$result = pg_exec($conn, "select * from table");
while ($row = pg_fetch_array($result))
{
     echo "data: ".$row["data"];
}

Can be a nice little time saver, PHP with MySQL has supported this for a while but I'm glad to see it extended to PostgreSQL...
up
2
gherson at snet dot net
23 years ago
PGSQL_BOTH is the default, meaning your array size will be doubled. 
If you specify this field (result type), include no quotes around it or you won't get any data, not even an error. 
Here's my wrapper function:
function SQL_fetch_array($result_ndx, $row, $result_type=PGSQL_ASSOC) {
   return pg_fetch_array($result_ndx, $row, $result_type);
up
1
gherson at snet dot net
23 years ago
In addition to returning "false if there are no more rows", pg_fetch_array will also trigger an E_WARNING.  You can temporarily turn that error reporting level off and suck out all your data like so:

<?php
$errRptLvl
= error_reporting();
error_reporting($errRptLvl & ~(E_WARNING));
      
list(
$i,$j)=array(0,0);
while (
$selection[$i++] = $this->fetchArray($j++)); // (fetchArray is a pg_fetch_array wrapper.)
error_reporting($errRptLvl); // Restore error reporting level.
unset($selection[$i-1]); // Delete the last, empty row.
return $selection;
?>
up
1
strata_ranger at hotmail dot com
15 years ago
Note that when using PGSQL_BOTH, numerically and associatively indexed fields are separate variables and treated as such:

<?php
$res
= pg_query("Select 'foo' as bar");

$data = pg_fetch_array($res, 0, PGSQL_BOTH);

var_dump($data);
// Array(2)
// {
//   [0] => string(3) "foo"
//   ["bar"] => string(3) "foo"
// }

// This won't affect $data['bar']
$data[0] = 'bar';

var_dump($data);
// Array(2)
// {
//   [0] => string(3) "bar"
//   ["bar"] => string(3) "foo"
// }
?>

If you want to have reference binding between your numeric and associative indexes, you'll have to establish that yourself:

<?php

$result
= pg_query("Select 'foo' as bar");

$data = pg_fetch_row($result);

// Establish references between column name/number
$from = $data;
foreach(
$from as $cx => $value)
{
   
$key = pg_field_name($result, $cx);
    if (
is_string($key)) $data[$key] =& $data[$cx];
}

var_dump($data);
// Array(2)
// {
//   [0] => &string(3) "foo"
//   ["bar"] => &string(3) "foo"
// }
// Note the reference binding between $data[0] and $data['bar']

$data[0] = 'baz';

var_dump($data);
// Array(2)
// {
//   [0] => &string(3) "baz"
//   ["bar"] => &string(3) "baz"
// }

?>
up
1
akm at e-nterart dot pl
21 years ago
(Timesaver) Be aware of the fact that keys in array returned by this function are (well, at least as of 4.2.3) of the same case as SQL column names (e.g. if your column name is ID then key name is also ID, not id or Id), and the keys in associative array are CASE SENSITIVE!!! So don't be surprised if you get unexpected results. Double check SQL column names and the key names.
up
0
devnull
19 years ago
In response to eth0's comment below about SELECT'ing from two tables where the tables have columns with the same names, you can get around this problem like this:

"SELECT table1.foo AS foo1, table2.foo AS foo2 FROM table1, table2"

In the associative array returned, the keys will be "foo1" and "foo2".
up
-1
anonymous
19 years ago
Hopefully most people realize this on their own, but the examples below where people tried to get creative with getting numerical or associative (not both) keys in the result are rather pointless. See the pg_fetch_assoc() and pg_fetch_row() for the built in functions that do this automatically. It's generally a better idea to use one of these other functions unless you *need* to access fields by both collumn name *and* index.
up
-1
enyo at www.red-link.com
21 years ago
Just because it is not really clear how to specify the result type, I poste this message.

I wrote a wrapper function which looks like this:

<?php
   
function db_fetch_array ($result, $row = NULL, $result_type = PGSQL_ASSOC)
    {
       
$return = @pg_fetch_array ($result, $row, $result_type);
        return
$return;
    }
?>

I think this way it is quite comfortable to get the arrays you want.
up
-1
elliot at nospam dot rightnowtech dot com
23 years ago
Just remember when you 'or die' to close your table(s) or you may get a confused look from non-internet explorer users.
up
-2
eth0 at fins
23 years ago
Please remember that if you have for example a table Customers with "cust_ID", "name" and "address" and another table Users with "u_ID","name" and "other" and then you SELECT WHERE cust_ID=u_ID then you'll get in the result array ONLY ONE "name" field, precisely the last one resulted from the select!!!
up
-3
Dave O
19 years ago
I found this out through help from the mailing lists.  If you need to reset the internal counter, use the pg_result_seek, similar to:

pg_result_seek($result, 0)

...plagiarized from the comment on the function's doc page.
To Top