Reputation: 17
I am trying to write a conditional statement which echo's the following messages :
if {the query executed bring results from the database
Process the query
echo 'Success' }
else {
If no results/ 0 results have been retrieved then
echo 'No results obtained'}
I am using PostgreSQL as my database. I am new to using PostgreSQL with PHP but so far I have managed to make my queries work. I am just confused on how I can do this and which part of the code this logic should be in. Is it before the query has been executed.
<?php
// Connecting, selecting database
$dbconn = pg_connect("host=localhost port=5432 dbname=sser user=postgres password=password")
or die('Could not connect: ' . pg_last_error());
$name = pg_escape_string($_POST['name']);
$name2 = pg_escape_string($_POST['name2']);
$query = " SELECT y.name, y.time, z.name, z.time
FROM
(SELECT * FROM departure_times WHERE name ='$name') as y,
(SELECT * FROM departure_times WHERE name ='$name2') as z
WHERE y.tram_id = z.tram_id ";
$result = pg_query($query) or die('Query failed: ' . pg_last_error());
// Printing results in HTML
echo "<table>\n";
echo "These are the following trams from '$name' to '$name2' ";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
// Free resultset
pg_free_result($result);
// Closing connection
pg_close($dbconn);
?>
Upvotes: 0
Views: 1916
Reputation: 5246
You have three situations to deal with:
In the first instance, pg_query()
returns the boolean value false
into the variable $result
; your or die()
clause handles this. In the second and third cases, $result
contains a result set resource which may or may not contain data, and you want to know whether it does or not.
The PHP API for PostgreSQL contains a handy function for just that purpose called pg_num_rows()
. This function takes a result set as its argument and returns an int showing the number of rows in the result. So your code would look something like this:
$result = pg_query($query)
or die('Query failed: ' . pg_last_error());
if (pg_num_rows($result) > 0)
{
echo "I found some data.";
}
else
{
echo "I got nothin'.";
}
Replace the echo
statements with your own logic.
Upvotes: 1