PHP

Retrieving Results of a Query to PostgreSQL

$result = pg_query();
pg_fetch_row($result);

The return value of a call to pg_query() is a pointer to a resultset that can be used with these functions:

  • pg_fetch_assoc() returns the current row in the resultset as an associative array

  • pg_fetch_object() returns the current row in the resultset as an object

  • pg_fetch_row() returns the current row in the resultset as a numeric array

  • pg_fetch_all() returns the complete resultset as an array of associative arrays

Retrieving Data from PostgreSQL
<table>
<tr><th>#</th><th>Quote</th><th>Author</th><th>Year<
  /th></tr>
<?php
  if ($db = @pg_connect('host=localhost port=5432
    dbname=hoshmand user=postgres
    password=abc123')) {
    $result = pg_query($db, 'SELECT * FROM quotes');
    while ($row = pg_fetch_row($result)) {
      vprintf(
 '<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td></
   tr>',
        $row
      );
    }
    pg_close($db);
  } else {
    echo '<tr><td colspan="4">Connection failed.</td></tr>';
  }
?>
</table>

The code uses pg_fetch_row() to read out all data from the quotes table.

Alternatively, pg_select() works similarly to pg_insert() and pg_update(). Just provide a database handle, a table name, and maybe a WHERE clause in the form of an array, and you get the complete resultset as an array of (associative) arrays.

$data = pg_select($db, 'quotes');

by BrainBellupdated
Advertisement: