我正在尝试编写一个条件语句,它回显以下消息:
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);
?>
最佳答案
您需要处理三种情况:
- 由于某些错误情况,查询失败。
- 查询成功并返回一行或多行数据。
- 查询成功运行,但没有返回任何数据,因为没有任何数据与查询条件匹配。
在第一个实例中,pg_query()
将 bool 值 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
语句。
关于php - 在 PHP PostgreSQL 查询结果中找到或未找到结果时显示消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35757198/