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"
// }
?>
pg_fetch_array
(PHP 4, PHP 5)
pg_fetch_array — Pobiera wiersz jako tablicę
Opis
pg_fetch_array() zwraca tablicę zawierającą dane z pobranego wiersza (rekordu).
pg_fetch_array() jest rozszerzeną wersją pg_fetch_row(). Oprócz zapisywania danych w tablicy wyników indeksowanej numerycznie, zapisuje je też używając indeksów przyporządkowujących (asocjacyjnych) tej tablicy, nazwy kolumn traktując jako klucze. Domyślnie zapisywane są oba rodzaje indeksów.
Informacja: Ta funkcja ustala wartość pól NULL na NULL.
pg_fetch_array() NIE jest znacznie wolniejsze, niż używanie pg_fetch_row(), oraz jest zdecydowanie łatwiejsze do użycia.
Parametry
- wynik
-
Identyfikator wyniku zapytania PostgreSQL, zwrócony przez pg_query(), pg_query_params() lub pg_execute() (między innymi).
- wiersz
-
Numer wiersza w wyniku do pobrania. Wiersze są numerowane od zera w górę. Jeśli pominięty, pobierany jest kolejny wiersz.
- typ_wyniku
-
Opcjonalny parametr kontrolujący w jaki sposób zwrócona tablica (ang. array) jest indeksowana. typ_wyniku jest stałą i może przyjąć następujące wartości: PGSQL_ASSOC, PGSQL_NUM oraz PGSQL_BOTH. Używając PGSQL_NUM, pg_fetch_array() zwróci tablicę z indeksami numerycznymi, użycie PGSQL_ASSOC zwróci wyłącznie indeksy asocjacyjne podczas, gdy PGSQL_BOTH, wartość domyślna, zwróci oba rodzaje indeksów - numeryczne i asocjacyjne.
Zwracane wartości
Tablica (ang. array) indeksowana numerycznie (zaczynając od zera) lub asocjacyjnie (indeksowana przez nazwy kolumn), lub tak i tak. Każda wartość w tablicy (ang. array) jest przedstawiona jako łańcuch (ang. string). Wartości NULL z bazy danych są zwracane jako NULL.
FALSE zostanie zwrócone jeśli wiersz przekracza ilość wierszy w całym zbiorze, nie ma więcej wierszy, lub dowolnym innym błędzie.
Rejestr zmian
| Wersja | Opis |
|---|---|
| 4.1.0 | Parametr wiersz stał się opcjonalnym. |
| 4.0.0 | Został dodany parametr typ_wyniku . |
Przykłady
Przykład #1 pg_fetch_array() - przykład
<?php
$polaczenie_z_baza = pg_pconnect("dbname=wydawca");
if (!$polaczenie_z_baza) {
echo "Wystąpił błąd.\n";
exit;
}
$wynik = pg_query($polaczenie_z_baza, "SELECT autor, email FROM autorzy");
if (!$wynik) {
echo "Wystąpił błąd.\n";
exit;
}
$tab = pg_fetch_array($wynik, 0, PGSQL_NUM);
echo $tab[0] . " <- Wiersz 1 Autor\n";
echo $tab[1] . " <- Wiersz 1 E-mail\n";
// Jako, że w PHP 4.1.0, parametr wiersz jest opcjonalny; można podać w zamian NULL,
// by podać typ_wyniku. Kolejne wywołanie funkcji pg_fetch_array zwróci
// następny wiersz.
$tab = pg_fetch_array ($wynik, 1, PGSQL_ASSOC);
echo $tab["autor"] . " <- Wiersz 2 Autor\n";
echo $tab["email"] . " <- Wiersz 2 E-mail\n";
$tab = pg_fetch_array($wynik);
echo $tab["autor"] . " <- Wiersz 3 Autor\n";
echo $tab[1] . " <- Wiersz 3 E-mail\n";
?>
Zobacz też:
- pg_fetch_row() - Pobiera wiersz jako tablicę z indeksami numerycznymi
- pg_fetch_object() - Pobiera wiersz jako obiekt
- pg_fetch_result() - Pobiera dane z wyniku
pg_fetch_array
23-Aug-2009 08:53
13-May-2005 09:21
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.
22-Feb-2005 05:52
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.
02-Feb-2005 09:59
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".
15-Sep-2003 01:55
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.
17-Jun-2003 04:45
(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.
13-Dec-2001 12:38
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...
28-Sep-2001 06:15
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!!!
23-Jul-2001 04:50
Just remember when you 'or die' to close your table(s) or you may get a confused look from non-internet explorer users.
28-Mar-2001 12:52
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.
06-Mar-2001 06:30
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;
?>
03-Jan-2001 05:14
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);
