【问题标题】:Displaying message when results have or have not been found in PHP PostgreSQL Query result在 PHP PostgreSQL 查询结果中找到或未找到结果时显示消息
【发布时间】:2016-03-02 20:14:25
【问题描述】:

我正在尝试编写一个回显以下消息的条件语句:

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'}

我使用 PostgreSQL 作为我的数据库。我是使用 PostgreSQL 和 PHP 的新手,但到目前为止,我已经设法使我的查询工作。我只是对如何做到这一点以及该逻辑应该在代码的哪一部分感到困惑。是在执行查询之前。

      <?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);
?>

【问题讨论】:

  • PHP.net 上 PGSQL 基础页面上的第一个示例:php.net/manual/en/pgsql.examples-basic.php
  • @SébastienVercammen 给定的页面对我来说没有显示...
  • @FirstOne 它显示了while ($line = pg_fetch_array($result, null, PGSQL_ASSOC)) 的工作原理。你不需要更多的把while变成if
  • 所以基本上我应该做以下事情: if {($line = pg_fetch_array($result, null, PGSQL_ASSOC)) 执行查询 echo 'Success' } else { echo ' Failure' }跨度>
  • @SébastienVercammen,OP 的代码已经获取数据。请再看一下这个问题。问题似乎出在check if there are any records and display a message accordingly 上。该链接甚至没有if xD

标签: php mysql sql database postgresql


【解决方案1】:

你需要处理三种情况:

  1. 由于某些错误条件,查询失败。
  2. 查询成功,返回一行或多行数据。
  3. 查询运行成功,但没有返回任何数据,因为没有一个符合查询条件。

在第一种情况下,pg_query() 将布尔值 false 返回到变量 $result 中;你的 or die() 子句处理这个问题。在第二种和第三种情况下,$result 包含可能包含或不包含数据的结果集资源,您想知道它是否包含。

用于 PostgreSQL 的 PHP API 包含一个方便的函数,称为 pg_num_rows()。此函数将结果集作为其参数,并返回一个显示结果中行数的 int。所以你的代码看起来像这样:

$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'.";
}

用您自己的逻辑替换 echo 语句。

【讨论】:

  • 这与我正在寻找的类似。 MySQL 示例使用了与此非常相似的东西,即 mysql_num_rows。非常感谢。真的很有帮助而且很清楚@Darwin von Corax
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2013-12-25
  • 2012-05-31
  • 2011-09-22
  • 2013-09-24
  • 1970-01-01
  • 1970-01-01
  • 2014-09-21
相关资源
最近更新 更多