gpt4 book ai didi

php - 从数据库中的结果返回下拉列表

转载 作者:搜寻专家 更新时间:2023-10-30 22:13:13 24 4
gpt4 key购买 nike

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

  $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>

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

我在如何实现这个方面遇到了一些麻烦,是否可以使用带有 SQL 查询的 IF 语句或其他方式来实现它,我是 PHP 和 SQL 的新手。

如果有任何帮助,我们将不胜感激。

最佳答案

尝试这样的事情:

$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 注入(inject)。

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

关于php - 从数据库中的结果返回下拉列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19860824/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com