Displaying PostgreSQL Column Names and Values via PHP
Sometimes in a PHP page it may be useful to not only retrieve data values from a PostgreSQL database table, but also to retrieve column names from the table. Listed below is an example of how to do this for PostgreSQL databases using PHP. This example uses PostgreSQL PHP libraries that have been available since PHP 4.
This example makes use of the pg_num_fields and pg_field_name functions to get a count of the number of columns, and then get the column name for each column index. The pg_fetch_row function is used to get the values.
<?php
$host = '127.0.0.1';
$port = '5432';
$database = 'sample';
$user = 'testuser';
$password = 'testpass';
$connectString = 'host=' . $host . ' port=' . $port . ' dbname=' . $database .
' user=' . $user . ' password=' . $password;
$link = pg_connect ($connectString);
if (!$link)
{
die('Error: Could not connect: ' . pg_last_error());
}
$query = 'select * from employee';
$result = pg_query($query);
$i = 0;
echo '<html><body><table><tr>';
while ($i < pg_num_fields($result))
{
$fieldName = pg_field_name($result, $i);
echo '<td>' . $fieldName . '</td>';
$i = $i + 1;
}
echo '</tr>';
$i = 0;
while ($row = pg_fetch_row($result))
{
echo '<tr>';
$count = count($row);
$y = 0;
while ($y < $count)
{
$c_row = current($row);
echo '<td>' . $c_row . '</td>';
next($row);
$y = $y + 1;
}
echo '</tr>';
$i = $i + 1;
}
pg_free_result($result);
echo '</table></body></html>';
?>