pg_fetch_result

(PHP 4 >= 4.2.0, PHP 5, PHP 7, PHP 8)

pg_fetch_resultRetorna valores de uma instância de resultado

Descrição

pg_fetch_result(PgSql\Result $result, string|false|null $row, mixed $field): string|false|null
pg_fetch_result(PgSql\Result $result, mixed $field): string|false|null

pg_fetch_result() retorna o valor de uma determinada linha e campo (coluna) em uma instância PgSql\Result.

Nota:

Esta função costumava ser chamada de pg_result().

Parâmetros

result

Uma instância de PgSql\Result, retornada por pg_query(), pg_query_params() ou pg_execute() (entre outras).

row

Número da linha no resultado a ser buscado. As linhas são numeradas de 0 para cima. Se omitido, a próxima linha será buscada.

field

Uma string representando o nome do campo (coluna) a ser buscado, caso contrário, um int representando o número do campo a ser buscado. Os campos são numerados de 0 para cima.

Valor Retornado

Booleano é retornado como "t" ou "f". Todos os outros tipos, incluindo arrays, são retornados como strings formatadas da mesma maneira padrão do PostgreSQL que você veria no programa psql. Os valores NULL do banco de dados são retornados como null.

false é retornado se row exceder o número de linhas no conjunto ou em qualquer outro erro.

Registro de Alterações

Versão Descrição
8.3.0 row agora é anulável.
8.1.0 O parâmetro result agora espera uma instância de PgSql\Result; anteriormente, um resource era esperado.

Exemplos

Exemplo #1 Exemplo de pg_fetch_result()

<?php
$db
= pg_connect("dbname=users user=me") || die();

$res = pg_query($db, "SELECT 1 UNION ALL SELECT 2");

$val = pg_fetch_result($res, 1, 0);

echo
"O primeiro campo da segunda linha é: ", $val, "\n";
?>

O exemplo acima produzirá:

O primeiro campo da segunda linha é: 2

Veja Também

add a note

User Contributed Notes 5 notes

up
6
ElDiablo
5 years ago
Please note that a very old bug (#76548) has been fixed in 7.2.8.

Previously, pg_fetch_result did not fetch the next row if $row was omitted.
It is now well the case, so bad use of the function can now cause some bugs in your codes.
up
1
newby_AT_nobletec_DOT_com
21 years ago
Comment on boolean fields:

If you retrieve a boolean value from the PostgreSQL database, be aware that the value returned will be either the character 't' or the character 'f', not an integer. So, the statement

if (pg_fetch_result($rsRecords,0,'blnTrueFalseField')) {
echo "TRUE";
} else {
echo "FALSE";
}

will echo "TRUE" in either case (True or False stored in the field). In order to work as expected, do this instead:

if (pg_fetch_result($rsRecords,0,'blnTrueFalseField') == 't') {
echo "TRUE";
} else {
echo "FALSE";
}
up
2
Alan U. Kennington
17 years ago
See bug #33809 http://bugs.php.net/bug.php?id=33809
Whether this really is a bug or a feature is not clear.
However, it is probably best to always put your column names in extra quotes.

$res = pg_query(...);
$colname = pg_field_name($res, $j);
pg_fetch_result($res, $i, "\"$colname\"");
up
-2
Alan U Kennington
17 years ago
In order to use upper case in pg_fetch_result column names, it is apparently necessary to include explicit quotation marks.

Thus when I do this sort of thing:

$res = pg_query(...);
$ncols = pg_num_fields($res);
for ($j = 0; $j < $ncols; ++$j) {
$colname[$j] = pg_field_name($res, $j);
$name = htmlspecialchars($colname[$j]);
print("Column $j name = \"$name\"\n");
$value = htmlspecialchars(pg_fetch_result($res, 0, $colname[$j]));
print("Column \"{$colname[$j]}\" value = \"$value\"\n");
}

I get this sort of thing:

[....]
Warning: pg_fetch_result() [function.pg-fetch-result]: Bad column offset specified in /.../view.php on line 247
Column 8 name = "VEC index"
Column "VEC index" value = ""

But if I change the $value line to this:

$value = htmlspecialchars(pg_fetch_result($res, 0, "\"$colname[$j]\""));

I get this:

[...]
Column 8 name = "VEC index"
Column "VEC index" value[0] = "47"

In my opinion, pg_fetch_result(...) should use the quotes already. In other words, this may be a bug in the PHP postgres library. It does not seem to be a documented feature of pg_fetch_result() although the postgresql manual documents it under "SQL syntax", "Lexical structure".

PHP version 5.1.4.
psql version 8.1.4.
up
-3
Akbar
19 years ago
Use can use pg_fetch_result when getting a value (like a smallint as in this example) returned by your stored procedure

<?php
$pgConnection
= pg_connect("dbname=users user=me");

$userNameToCheckFor = "metal";

$result = pg_query($pgConnection, "SELECT howManyUsersHaveThisName('$userNameToCheckFor')");

$count = pg_fetch_result($result, 0, 'howManyUsersHaveThisName');

?>
To Top