11.5 Retrieving Objects from the Database


When working with object-oriented PHP, it can be helpful to retrieve data from the table as objects. Therefore PHP provides a command called pg_fetch_object, which can be used like pg_fetch_array and pg_fetch_row. To see how the command works, first create a table and insert some data:

 phpbook=# CREATE TABLE plant(id int4, name text, color text); CREATE phpbook=# INSERT INTO plant VALUES (1, 'Sambucus nigra', 'yellow'); INSERT 116394 1 phpbook=# INSERT INTO plant VALUES (2, 'Abies', 'green'); INSERT 116395 1 phpbook=# INSERT INTO plant VALUES (3, 'Colchicum autumnale', 'pink'); INSERT 116396 1 

If no error occurred, you have created a table containing information about three plants and their colors. In the next step, the data should be retrieved as objects.

The next example shows pg_fetch_object in action:

 <?php         $connstr = "dbname=phpbook user=postgres host=localhost";         $dbh = pg_connect($connstr);         $sql = "SELECT id, name, color FROM plant WHERE id=1";         $result = pg_exec($dbh, $sql);         $data = pg_fetch_object($result, 0);         echo "If you have the flu drink some tea made of $data->name<br>\n";         echo "Take the $data->color parts of the plant and boil it.<br>\n";         pg_close($dbh); ?> 

To access the various components of the object, the -> operator must be used. The only difference between using an array and using objects lies in the syntax you have to use.

Let's take a look at the output of the script:

 If you have the flu drink some tea made of Sambucus nigra Take the yellow parts of the plant and boil it. 

The data is displayed just as if you were using arrays.



PHP and PostgreSQL. Advanced Web Programming2002
PHP and PostgreSQL. Advanced Web Programming2002
ISBN: N/A
EAN: N/A
Year: 2004
Pages: 201

flylib.com © 2008-2017.
If you may any questions please contact us: flylib@qtcs.net