我正在用一個查詢生成器構建一個動態應用程序,該查詢生成器由四個選擇列表組成,用戶可以在其中輸入表,列,運算符和屬性名稱。現在我也希望用戶能夠選擇ALL。所以用戶應該只能選擇表格和列名(= ALL)。但我不知道如何過濾掉where子句。這是目前我的PHP腳本:如何過濾查詢生成器中的where子句?
<?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 ";";
}
?>
動態構建查詢字符串,只在3個必填字段不爲空時添加'WHERE'條件。順便說一句,您應該用佔位符替換值,並使用數據庫名,表名和列名白名單來避免sql注入/中斷查詢。 – jeroen
是的,這是主意。但是,如何做@ @ jeroen? –