PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

pg_fetch_result> <pg_fetch_assoc
Last updated: Fri, 15 Aug 2008

view this page in

pg_Fetch_Object

(PHP 4, PHP 5)

pg_Fetch_Objectobtener una fila en forma de objeto

Descripción

object pg_fetch_object ( int $result , int $row [, int $result_type ] )

Devuelve: Un objeto cuyas propiedades se corresponden con los campos de la fila obtenida, o FALSE si no hay más filas.

pg_fetch_object() es parecida a pg_fetch_array(), con una diferencia - se devuelve un objeto, en vez de un array. Indirectamente, eso significa que solo puedes acceder a los datos por medio de su nombre de campo, y no a través de sus posiciones (los números son nombres de propiedad invalidos).

El tercer parámetro opcional result_type en pg_fetch_object() es una constante y puede tomar cualquiera de los siguientes valores: PGSQL_ASSOC, PGSQL_NUM, y PGSQL_BOTH.

Note: Result_type se añadio en PHP 4.0.

Referente a la velocidad, la función es identica a pg_fetch_array(), y practicamente tan rápida como pg_fetch_row() (la diferencia es insignificante).

Ver también: pg_fetch_array() y pg_fetch_row().

Example #1 Postgres fetch object

<?php 
$database 
"verlag";
$db_conn pg_connect ("localhost""5432"""""$database);
if (!
$db_conn): ?>
    <H1>Failed connecting to postgres database <? echo $database ?></H1> <?
    
exit;
endif;

$qu pg_exec ($db_conn"SELECT * FROM verlag ORDER BY autor");
$row 0// postgres needs a row counter other dbs might not 

while ($data pg_fetch_object ($qu$row)):
    echo 
$data->autor." (";
    echo 
$data->jahr ."): ";
    echo 
$data->titel."<BR>";
    
$row++;
endwhile; 
?>

<PRE><?php
$fields
[] = Array ("autor""Author");
$fields[] = Array ("jahr",  "  Year");
$fields[] = Array ("titel"" Title");

$row0// postgres needs a row counter other dbs might not
while ($data pg_fetch_object ($qu$row)):
    echo 
"----------\n";
    
reset ($fields);
    while (list (,
$item) = each ($fields)):
        echo 
$item[1].": ".$data->$item[0]."\n";
    endwhile;
    
$row++;
endwhile;
echo 
"----------\n"?>
</PRE> <?php
pg_freeResult 
($qu);
pg_close ($db_conn);
?>



pg_fetch_result> <pg_fetch_assoc
Last updated: Fri, 15 Aug 2008
 
add a note add a note User Contributed Notes
pg_Fetch_Object
ekevu at yahoo dot com
03-Jul-2007 04:36
PostgreSQL boolean true becomes string "t"
PostgreSQL boolean false becomes string "f"
This is ambiguous, and leads to code duplication. I wonder why aren't the types correctly typed when fetching values. We could at least have an optional parameter to enable that.
robeddielee at hotmail dot com
27-Jan-2006 08:38
I noticed that many people use FOR loops to extract query data. This is the method I use to extract data.

<?php
 
@$members = pg_query($db_conn, 'SELECT id,name FROM boards.members ORDER BY name;');
 if (
$members AND pg_num_rows($members)) {
  while (
$member = pg_fetch_object($members)) {
   echo
$member->name.' ('.$member->id.')';
  }
 }
?>

If an error occurs (or nothing is returned) in the above code nothing will output. An ELSE clause can be added to the IF to handle query errors (or nothing being returned). Or a seperate check can be performed for the event that nothing is returned by using an ELSEIF clause.

I like this method because it doesn't use any temporary counter variables.
oracle dot shinoda at gmail dot com
16-Nov-2004 03:13
If you're wanting to use objects for your results, but are put off because you can't seem to apply a function to each field of the result (like stripslashes for example), try this code:

<?php
// Code to connect, do query etc etc...

$row = pg_fetch_object($result);
$vars = get_object_vars($row);
foreach (
$vars as $key => $var )
{
   
$row->{$key} = stripslashes($var);
}

?>
michiel at minas-2 dot demon dot nl
16-Jun-2004 05:13
Something I have learned to use:

$result=$pg_query (...);
$num = pg_numrows($result);

for($count=0;$count < $num && $data=pg_fetch_object($result,$count);$count++)
{
    printf("<tr>\n");
    printf("    <td>%s</td>\n",$data->foo);
    printf("    <td>%s</td>\n",$data->bar);
    printf("</tr>\n");
}
Lars at dybdahl dot dk
14-Oct-2003 05:43
When you retrieve the contents of a "timestamp with timezone" field, this will set the environment's timezone variables. Therefore, this is dangerous:

$s=$row->mydatefield;
$unixtimestamp=postgresqltimestamp2unix($s);
echo date("Y-m-d H:i:s",$unixtimestamp);

Here, postgresqltimestamp2unix is a function that converts the postgresql timestamp to Unix. The retrieval of the field data in the first line of the example above will influence the timezone used in date() in the third line.
ian at eiloart dot com
10-Feb-2003 04:27
This isn't all that useful. If you do, for example, foreach($row as $field) then you still get every value twice!

You can do something like this, though:

foreach ($line as $key => $cell){
     if (! is_numeric($key)){
                echo "<td>$key $cell</td>";
     }
}

is is_numeric strict enough?
inbox at bucksvsbytes dot com
16-Mar-2002 06:13
The result_type arg is either invalid or incorrectly documented, since the "result_type is optional..." paragraph is copied verbatim from pg_fetch_array, and the PGSQL_NUM option is in conflict with the preceding paragraph's, "you can only access the data by the field names, and not by their
offsets."

pg_fetch_result> <pg_fetch_assoc
Last updated: Fri, 15 Aug 2008
 
 
show source | credits | sitemap | contact | advertising | mirror sites