我使用查询构建器构建动态应用程序,该构建器由四个选择列表组成,用户可以在其中输入表,列,运算符和属性名称。现在我也希望用户能够选择ALL。因此用户应该只选择表和列名(= ALL)。但我不知道如何过滤掉where子句。这是我目前的PHP脚本:
<?php
include "connect.php";
$table = $_GET['tableSelected'];
$field = $_GET['fieldSelected'];
$attribute = $_GET['attributeSelected'];
$operator = $_GET['operatorSelected'];
$tableList = $_GET['tableList'];
$fieldList = $_GET['fieldList'];
$attributeList = $_GET['attributeList'];
$fieldstr = $fieldList . ",ST_AsGeoJSON(ST_Transform(l.geom,4326))";
$sql = "SELECT $fieldstr
FROM $table l
WHERE $field $operator '{$attribute}'";
if (!$response = pg_query($conn, $sql)) {
echo "A query error occured.\n";
exit;
}
while ($row = pg_fetch_row($response)) {
foreach ($row as $i => $attr){
echo $attr.", ";
}
echo ";";
}
?>
答案 0 :(得分:1)
您应该动态构建字符串,并且只有在该部分的必填字段不为空时才添加WHERE
条件。
例如:
$sql = "SELECT {$fieldstr}
FROM {$table}";
if (!empty($field) && !empty($operator) && !empty($attribute)) {
$sql .= " WHERE {$field} {$operator} '{$attribute}'";
}
顺便说一下,你应该用占位符替换值,并使用white-lists表示数据库,表和列名以及运算符,以避免sql注入/破坏你的查询。