pg_fetch_array
(PHP 4, PHP 5)
pg_fetch_array — Возвращает строку результата в виде массива
Описание
$result
[, int $row
[, int $result_type
= PGSQL_BOTH
]] )pg_fetch_array() возвращает массив, соответствующий выбранной строке (записи).
pg_fetch_array() расширенная версия функции pg_fetch_row(). Эта функция способна сохранить данные не только с цифровыми индексами, но и с ассоциативными (имя поля). По умолчанию хранит и те и другие.
Замечание: Эта функция устанавливает NULL-поля в значение
NULL
PHP.
pg_fetch_array() выполняется незначительно медленнее чем pg_fetch_row(), но значительно проще в использовании.
Список параметров
-
result
-
Ресурс результата запроса PostgreSQL, возвращенный функцией pg_query(), pg_query_params() или pg_execute() (и прочих).
-
row
-
Номер строки в result для выборки. Строки пронумерованы с 0 по возрастанию. Если параметр опущен или передан
NULL
будет выбрана следующая строка. -
result_type
-
Необязательный параметр для управления типом индексации возвращаемого массива (array). Параметр
result_type
обязателен и может принимать следующие значения:PGSQL_ASSOC
,PGSQL_NUM
иPGSQL_BOTH
. При указанииPGSQL_NUM
, pg_fetch_array() вернет массив с цифровыми индексами, в случаеPGSQL_ASSOC
вернет только ассоциативные индексы, а в случаеPGSQL_BOTH
(используется по умолчанию) -- цифровые и ассоциативные индексы.
Возвращаемые значения
Массив (array) с цифровыми индексами (начиная с 0),
либо ассоциативнми (по имени поля), либо с обеими типами индексов.
Каждое значение в массиве (array) представлено как
строка (string). Значение NULL возвращается как
NULL
.
Функция возвращает FALSE
если row
выходит за рамки
количества строк в выборке, или отсутствия строк, или в случае любой другой ошибки.
Список изменений
Версия | Описание |
---|---|
4.1.0 |
Параметр row стал необязательным.
|
Примеры
Пример #1 Пример использования pg_fetch_array()
<?php
$conn = pg_pconnect("dbname=publisher");
if (!$conn) {
echo "Произошла ошибка.\n";
exit;
}
$result = pg_query($conn, "SELECT author, email FROM authors");
if (!$result) {
echo "Произошла ошибка.\n";
exit;
}
$arr = pg_fetch_array($result, 0, PGSQL_NUM);
echo $arr[0] . " <- Row 1 Author\n";
echo $arr[1] . " <- Row 1 E-mail\n";
// С версии PHP 4.1.0 параметр row стал опциональным,
// для передечи result_type вместо row можно передать NULL.
// Успешные вызовы pg_fetch_array вернут следующий ряд.
$arr = pg_fetch_array($result, NULL, PGSQL_ASSOC);
echo $arr["author"] . " <- Row 2 Author\n";
echo $arr["email"] . " <- Row 2 E-mail\n";
$arr = pg_fetch_array($result);
echo $arr["author"] . " <- Row 3 Author\n";
echo $arr[1] . " <- Row 3 E-mail\n";
?>
Смотрите также
- pg_fetch_row() - Выбирает строку результата запроса и помещает данные в массив
- pg_fetch_object() - Выбирает строку результата запроса и возвращает данные в виде объекта
- pg_fetch_result() - Возвращает запись из результата запроса
- PHP Руководство
- Функции по категориям
- Индекс функций
- Справочник функций
- Расширения для работы с базами данных
- Расширения для работы с базами данных отдельных производителей
- PostgreSQL
- pg_affected_rows
- pg_cancel_query
- pg_client_encoding
- pg_close
- pg_connect_poll
- pg_connect
- pg_connection_busy
- pg_connection_reset
- pg_connection_status
- pg_consume_input
- pg_convert
- pg_copy_from
- pg_copy_to
- pg_dbname
- pg_delete
- pg_end_copy
- pg_escape_bytea
- pg_escape_identifier
- pg_escape_literal
- pg_escape_string
- pg_execute
- pg_fetch_all_columns
- pg_fetch_all
- pg_fetch_array
- pg_fetch_assoc
- pg_fetch_object
- pg_fetch_result
- pg_fetch_row
- pg_field_is_null
- pg_field_name
- pg_field_num
- pg_field_prtlen
- pg_field_size
- pg_field_table
- pg_field_type_oid
- pg_field_type
- pg_flush
- pg_free_result
- pg_get_notify
- pg_get_pid
- pg_get_result
- pg_host
- pg_insert
- pg_last_error
- pg_last_notice
- pg_last_oid
- pg_lo_close
- pg_lo_create
- pg_lo_export
- pg_lo_import
- pg_lo_open
- pg_lo_read_all
- pg_lo_read
- pg_lo_seek
- pg_lo_tell
- pg_lo_truncate
- pg_lo_unlink
- pg_lo_write
- pg_meta_data
- pg_num_fields
- pg_num_rows
- pg_options
- pg_parameter_status
- pg_pconnect
- pg_ping
- pg_port
- pg_prepare
- pg_put_line
- pg_query_params
- pg_query
- pg_result_error_field
- pg_result_error
- pg_result_seek
- pg_result_status
- pg_select
- pg_send_execute
- pg_send_prepare
- pg_send_query_params
- pg_send_query
- pg_set_client_encoding
- pg_set_error_verbosity
- pg_socket
- pg_trace
- pg_transaction_status
- pg_tty
- pg_unescape_bytea
- pg_untrace
- pg_update
- pg_version
Коментарии
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);
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;
?>
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.
Just remember when you 'or die' to close your table(s) or you may get a confused look from non-internet explorer users.
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!!!
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...
(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.
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.
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".
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.
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.
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"
// }
?>