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

标签 php sql postgresql where-clause

我在 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/

相关文章:

mysql - 两次指定表名作为更新目标和单独的数据源

mysql - 我的 mysql 5.7 语法有什么问题?

ruby-on-rails - 使用本地哈希/数组更新许多记录的单个 Postgres 查询

postgresql - Docker compose fiware WireCloud 数据持久性未从卷加载

php - 将 int 转换为 float/double

PHP preg_match 查找整个单词

sql - 在 Management Studio 中查看表列表所需的权限

sql - 从 PostgreSQL 表中选择第 N 个值并在查询中使用

php - 是否可以在action.php中自动插入数据?

php - mySQL PHP 更新