From: | Tomas Vondra <tv(at)fuzzy(dot)cz> |
---|---|
To: | PJ <af(dot)gourmet(at)videotron(dot)ca> |
Cc: | Matthias Ritzkowski <matthiar(at)gmail(dot)com>, pgsql-php(at)postgresql(dot)org |
Subject: | Re: display query results |
Date: | 2008-07-30 21:30:26 |
Message-ID: | 4890DD72.2020400@fuzzy.cz |
Views: | Raw Message | Whole Thread | Download mbox | Resend email |
Thread: | |
Lists: | pgsql-php |
See, you're working with a database - you execute a query but the data
(result) is still in the database. The '$result' variable represents
just a link to the data in the database - that's why it prints 'Resource
id #3'. That's almost the same as the '$connection' variable - I guess
you don't expect this to print all the data in the database:
<?php
$connection = pg_connect('...');
echo $connection;
?>
So you have to fetch the data from resultset from the database process
into PHP, and that's what pg_fetch_* functions are for. Each time you
call pg_fetch_array($result) it fetches and returns the next row (or
FALSE if there are no more rows).
The rows returned by pg_fetch_array are associative arrays, keys being
the field names.
So something like this should work:
<?php
$connection = pg_connect('...');
$result = pg_query('SELECT field_a, field_b FROM my_table');
while ($row = pg_fetch_array($result)) {
echo 'field a: ', $row['field_a'],"\n";
echo 'field b: ', $row['field_b'],"\n\n";
}
?>
If it prints nothing, then the resultset is empty - try to run the same
query pro psql or some other SQL interface.
Tomas
> Doesn't work... and I feel totally lost. I don't understand the
> pg_fetch_* stuff at all.
> One would think that my query should return the text that is in the
> field. The database is quite correct and does work with php since it
> comes from an older web-site that someone else programmed for me. I'm
> using it to practice and learn. :)
>
> Matthias Ritzkowski wrote:
>> Try this:
>>
>> $db = pg_connect("host=localhost port=5432 dbname=med user=med
>> password=0tscc71");
>>
>> if (!$db)
>> {
>> die("Could not open connection to database server");
>> }
>>
>> // generate and execute a query
>> $query = "SELECT description FROM glossary_item WHERE
>> name='Alcohol'";
>> $result = pg_query($db, $query) or die("Error in query: $query.
>> " . pg_last_error($db));
>>
>> // Print result on screen
>> while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
>> foreach ($line as $col_value) {
>> echo $col_value."<br />";
>> }
>>
>> pg_close($db);
>>
>>
>> The result set is an array, You just need to loop through it. The php
>> manual has some nice examples that helped me get started.
>> --------------------------------
>>
>>
>> Matthias Ritzkowski
>>
>>
>
>
From | Date | Subject | |
---|---|---|---|
Next Message | Tomas Vondra | 2008-07-30 21:33:58 | Re: display query results |
Previous Message | Andy Shellam | 2008-07-30 21:23:08 | Re: display query results |