在php中创建查询

时间:2014-09-17 18:35:30

标签: php mysql postgresql compiler-errors echo

我必须从postgreSQL对世界数据库编写2个查询。现在我在编译程序时遇到错误,我无法弄清楚原因。我正在处理的2个查询是

1. Find the district and population of all cities named Springfield. 
   Sort results from most populous to least populous. (3 results)
2. Find the name, district, and population of each city in Brazil (country code BRA). 
   Order results by city name alphabetically. (250 results)

然后我必须在表格中打印出结果。我在程序的这一部分遇到了一些问题,我必须打印出结果。我相信我有正确的SELECT语句来获取正确的信息,我只是对如何在表中显示信息感到困惑。任何帮助将不胜感激。这是我的代码。

<html>
<head/>
<body>
<form method = "POST" action ="<?= $_SERVER['PHP_SELF'] ?>" >
<table>
    <tr><td>Select Query</td><td><select name="query">
    <option value="1">Query 1</option>
    <option value="2">Query 2</option>
</select>
</td></tr>
</tr><td colspan="2"><input type="submit" name="execute" value="Generate" /></td></tr>
</table>
</form>

<?php
    include("public_html/secure/database.php");
    $con = ph_connect(HOST." ".DBNAME." ".USERNAME." ".PASSWORD);
    if(isset($_POST["execute"])){

    switch($_POST["query"]){

            case 1:
                    $q = "SELECT district, population FROM lab2.city WHERE (city = 'Springfield') ORDER BY population DESC";
                    $result = pg_query($q) or die('Query failed: ' . pg_last_error());
                    break;

            case 2:

                   $q = "SELECT name, district, population FROM lab2.city WHERE (country_code = 'BRA') ORDER BY name";      
                    $result = pg_query($q) or die('Query failed: ' . pg_last_error());                                      
                    break;
            }

                    echo "<table>\n";
                    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";

            pg_free_result($result);
            pg_close($con);


?>

</body>
</html>

当我使用php lab2.php命令时,我现在得到的错误是

以下是第一个查询的正确输出示例。

district    population
Massachusetts   152082
Missouri    151580
Illinois    111454

1 个答案:

答案 0 :(得分:3)

首先,您应该在$ q变量中的字符串周围加引号;

示例:

$q = "Select district, population FROM lab2.city WHERE (city = 'Springfield') ORDER BY population DESC";