dongsi1944
dongsi1944
2016-03-02 20:14

在PHP PostgreSQL查询结果中找到或未找到结果时显示消息

已采纳

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>
";
echo "These are the following trams from '$name' to '$name2' ";
while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) {
echo "\t<tr>
";
foreach ($line as $col_value) {
    echo "\t\t<td>$col_value</td>
";
  }
  echo "\t</tr>
";
}
echo "</table>
";

// Free resultset
pg_free_result($result);


// Closing connection
pg_close($dbconn);
?>
  • 点赞
  • 写回答
  • 关注问题
  • 收藏
  • 复制链接分享
  • 邀请回答

1条回答

  • douba6361 douba6361 5年前

    You have three situations to deal with:

    1. The query fails due to some error condition.
    2. The query succeeds and returns one or more rows of data.
    3. The query runs successfully, but returns no data because none match the query conditions.

    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.

    点赞 评论 复制链接分享