1

我正在使用以下代码从数据库中检索数据:

  $conn = pg_connect("host=********* port=5432
  dbname=******* user=******* password=*********");
  $result = pg_query ($conn, "SELECT Column1, Column2, Column3, Price, Column4 FROM phones ORDER BY Price");
  echo "<table border='1'>";
  echo "<tr>  
            <th></th>
            <th>Column1</th>
            <th>Column2</th>
            <th>Column3</th>
            <th>Price</th>
            <th>Column4</th> </tr>";
  while ($a = pg_fetch_row($result)) {
    echo "<tr>";
    echo "<td> <form> <input type='checkbox'> </form> </td>";
    for ($j = 0; $j < pg_num_fields($result); $j++) {
      echo "<td>" . $a[$j] . "</td>";
    }
    echo "</tr>\n";
  }
echo "</table>\n";

我在同一页面上也有一个基本表格:

<form name="form2"action="" method="GET">
<select name="highlow">
    <option value="All">All</option>
    <option value="higher">higher</option>
    <option value="less">less</option>
</select>
Price:<input type="text" name="price"/>
<input type="submit" name="submit" value="Submit" />
</form>

当从下拉菜单中选择全部时,我希望显示所有结果,更高=价格高于表单文本字段中指定价格的所有结果,低于但低于指定价格的所有结果相同。

我在如何实现这一点上遇到了一些麻烦,无论如何使用带有 SQL 查询的 IF 语句来实现它或其他方式,我对 PHP 和 SQL 很陌生。

任何帮助都会非常感谢。

4

3 回答 3

1

完全同意 Joshua,如果您在 while 循环之前移动以下行,您应该使用准备好的语句来防止 SQL 注入和另一个建议(代码改进)

$numFields = pg_num_fields($result);

因为您的结果集的字段数量始终相同,并且在您现有的代码中,您每次都在获取 while 和 For 循环。

可以帮助你。

于 2013-11-08T14:42:08.733 回答
1

我也同意 joshua 和 Himanshu Sharma 的观点,但您也可以在循环内的 php 中编写逻辑。但坦率地说,将 if(condition) 放在循环内效率不高。这里的替代方法是代码

while ($a = pg_fetch_row($result)) {
echo "<tr>";
echo "<td> <form> <input type='checkbox'> </form> </td>";
for ($j = 0; $j < pg_num_fields($result); $j++) {
if($j==4)
{if($_GET['highlow'] === 'higher')
  if($_GET[price]<=$a[$j])
  echo "<td>" . $a[$j] . "</td>";
  else
  if($_GET[price]>=$a[$j])
  echo "<td>" . $a[$j] . "</td>";
}}}
于 2013-11-08T15:23:04.410 回答
1

尝试这样的事情:

$query = 'SELECT Column1, Column2, Column3, Price, Column4 FROM phones ';
if($_GET['submit']) { // name attribute of your submit button
    // we'll get here only if the submit button is used
    if($_GET['highlow'] === 'higher') {
        $query .= 'WHERE Price > ' . ((int) $_GET['price']);
    } else if($_GET['highlow'] === 'less') {
        $query .= 'WHERE Price < ' . ((int) $_GET['price']);
    }
}

$query .= ' ORDER BY Price';

$result = pg_query ($conn, $query);

当然,您应该使用准备好的语句来防止 SQL 注入。

免责声明:这是一个快速制作的草稿,不会赢得选美比赛等;)

于 2013-11-08T14:06:31.443 回答