我正在尝试编写一个条件语句,该语句回显以下消息:
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()
返回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
语句替换为您自己的逻辑。