【发布时间】: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上。该链接甚至没有ifxD
标签: php mysql sql database postgresql