PHP.mk документација

pg_fetch_array

Почист и полокален преглед на PHP референцата, со задржана структура од PHP.net и подобра читливост за примери, секции и белешки.

function.pg-fetch-array.php PHP.net прокси Преводот се освежува
Оригинал на PHP.net
Патека function.pg-fetch-array.php Локална патека за оваа страница.
Извор php.net/manual/en Оригиналниот HTML се реупотребува и локално се стилизира.
Режим Прокси + превод во позадина Кодовите, табелите и белешките остануваат читливи во истиот тек.
pg_fetch_array

Референца за `function.pg-fetch-array.php` со подобрена типографија и навигација.

function.pg-fetch-array.php

pg_fetch_array

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

pg_fetch_arrayЗеми ред како низа

= NULL

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

pg_fetch_array() враќа низа што одговара на земениот ред (запис).

pg_fetch_array() е проширена верзија на pg_fetch_row(). Покрај складирањето на податоците во нумерички индекси (број на поле) во низата со резултати, може да ги складира податоците и користејќи асоцијативни индекси (име на поле). Стандардно ги складира двата индекси.

Забелешка: Оваа функција ги поставува NULL полињата на PHP null value.

pg_fetch_array() НЕ е значително побавен од користењето pg_fetch_row(), и е значително полесен за употреба.

Параметри

result

Еден PgSql\Result инстанца, вратена од pg_query(), pg_query_params() or pg_execute()инстанца, или ознаката за завршување на PostgreSQL командата поврзана со резултатот

row

Реден број во резултатот за преземање. Редовите се нумерирани од 0 нагоре. Ако е изоставен или null, следниот ред се презема.

mode

Опционален параметар што контролира како вратениот array е индексиран. mode е константа и може да ги земе следните вредности: PGSQL_ASSOC, PGSQL_NUM and PGSQL_BOTH. Користејќи PGSQL_NUM, функцијата ќе врати низ со нумерички индекси, користејќи PGSQL_ASSOC ќе врати само асоцијативни индекси додека PGSQL_BOTH ќе врати и нумерички и асоцијативни индекси.

Вратени вредности

Еден array индексиран нумерички (почнувајќи од 0) или асоцијативно (индексиран по име на поле), или и двете. Секоја вредност во array е претставена како string. База NULL вредностите се враќаат како null.

false се враќа ако row го надминува бројот на редови во множеството, нема повеќе редови или на која било друга грешка. Земањето од резултат на барање различно од SELECT исто така ќе врати false.

Дневник на промени

Верзија = NULL
8.1.0 На result параметарот очекува PgSql\Result инстанца сега; претходно, а resource се очекуваше.

Примери

Пример #1 pg_fetch_array() example

<?php

$conn
= pg_pconnect("dbname=publisher");
if (!
$conn) {
echo
"An error occurred.\n";
exit;
}

$result = pg_query($conn, "SELECT author, email FROM authors");
if (!
$result) {
echo
"An error occurred.\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";

// The row parameter is optional; NULL can be passed instead,
// to pass a result_type. Successive calls to pg_fetch_array
// will return the next row.
$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";

?>

Види Исто така

Белешки од корисници за да означиме кој било валиден PHP израз.

mkb на ele dot uri dot edu
figroc at gmail dot com
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.
jesse на sokieserv dot dhs dot org
figroc at gmail dot com
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...
gherson на snet dot net
yasuo_ohgaki at hotmail dot com
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);
gherson на snet dot net
yasuo_ohgaki at hotmail dot com
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;
?>
akashwebdev at gmail dot com
пред 16 години
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"
// }

?>
akm на e-nterart dot pl
пред 22 години
(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.
devnull
21 години пред
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".
anonymous
20 години пред
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.
enyo на www.red-link.com
пред 22 години
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.
eth0 на fins
figroc at gmail dot com
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!!!
elliot на nospam dot rightnowtech dot com
figroc at gmail dot com
Just remember when you 'or die' to close your table(s) or you may get a confused look from non-internet explorer users.
Dave O
21 години пред
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.
Навигација

Прелистувај сродни теми и функции.

На оваа страница

Автоматски outline од активната документација.

Насловите ќе се појават тука по вчитување.

Попрегледно читање

Примерите, changelog табелите и user notes се визуелно издвоени за да не се губат во долгата содржина.

Брз совет Користи го outline-от Скокни директно на главните секции од активната страница.
Извор Оригиналниот линк останува достапен Кога ти треба целосен upstream context, отвори го PHP.net во нов tab.