gpt4 book ai didi

php - 从 PHP 为 Postgresql 查询构建交互式 WHERE 子句

转载 作者:行者123 更新时间:2023-11-29 13:34:39 25 4
gpt4 key购买 nike

我在 Linux 上使用 Postgresql 9.2 和 PHP 5.5。我有一个包含“患者”记录的数据库,我正在网页上显示这些记录。这工作正常,但现在我需要添加交互式过滤器,以便它根据用户使用的过滤器只显示某些类型的记录,比如有 10 个复选框,我从中构建一个基于该信息的临时 WHERE 子句和然后实时重新运行查询。我有点不清楚该怎么做。

如何使用 PHP 来解决这个问题?

最佳答案

您需要做的就是使用 $_POST 或 $_GET 接收用户选择的过滤器的所有数据,然后创建一个带有循环的小函数,以按照您的查询需要的方式连接所有内容。

是这样的……在这种情况下,您的数据库中只有一个字段可以匹配。这是一个简单的场景,您需要创建更多字段,以便在每种情况下添加您真正需要的字段,不要太复杂。

<?php 

//recieve all the filters and save them in array

$keys[] = isset($_POST['filter1'])?'$_POST['filter1']':''; //this sends empty if the filter is not set.
$keys[] = isset($_POST['filter2'])?'$_POST['filter2']':'';
$keys[] = isset($_POST['filter3'])?'$_POST['filter3']':'';


//Go through the array and concatenate the string you need. Of course, you might need AND instead of OR, depending on what your needs are.
foreach ($keys as $id => $value) {
if($id > 0){
$filters.=" OR ";
}
$filters.=" your_field = '".$value."' ";
}

//at this point $filters has a string with all your

//Then make the connection and send the query. Notice how the select concatenates the $filters variable

$host = "localhost";
$user = "user";
$pass = "pass";
$db = "database";

$con = pg_connect("host=$host dbname=$db user=$user password=$pass")
or die ("Could not connect to server\n");

$query = "SELECT * FROM table WHERE ".$filters;

$rs = pg_query($con, $query) or die("Cannot execute query: $query\n");

while ($row = pg_fetch_row($rs)) {
echo "$row[0] $row[1] $row[2]\n";

//or whatever way you want to print it...
}

pg_close($con);

?>

上面的代码将从发送 3 个变量的表单中获取变量(假设它们都对应于数据库中的 SAME 字段,并生成一个字符串用作 WHERE 子句。

如果您要过滤数据库的多个字段,您需要做的就是注意如何将用户输入与您的字段相匹配。

注意:出于实际原因,我没有在此处添加它......但是请清理用户输入......在查询中使用用户控制的数据之前,请始终清理用户输入。

祝你好运。

关于php - 从 PHP 为 Postgresql 查询构建交互式 WHERE 子句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15824253/

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