I'm making some type of query builder and I want to implement a button to add a AND statement to my query. I made a version where I have 1 AND statement implemented but it's a bit devious and I want the user to have the ability to do more than one AND statement. This the code I have at the moment.
UPDATEDThis is my .php file:
<?php
include "connect.php";
//Ophalen van de waarden uit de tabel(len) en veld(en)
$table = $_GET['tableSelected'];
$field = $_GET['fieldSelected'];
$attribute = $_GET['attributeSelected'];
$operator = $_GET['operatorSelected'];
$fieldList = $_GET['fieldList'];
$fieldstr = $fieldList . ",ST_AsGeoJSON(ST_Transform(l.geom,4326))";
$sql = "SELECT $fieldstr
FROM $table l";
if (!empty($field) && !empty($operator) && !empty($attribute)) {
$sql .= " WHERE {$field} {$operator} '{$attribute}' AND {$field}";
};
//echo ($sql);
?>
A few things:
- Your current sql will fail if the first pair is emptied as there will be no
WHERE
but onlyAND
clauses. - Using arrays in html allows you to use arrays in php, making everything a lot easier to process by looping over it.
A simple example:
html:
<select name="field[]">...</select>
<select name="operator[]">...</select>
<select name="value[]">...</select>
You can use javascript to add more pairs of the exact same code.
Now in php your $_POST
variables will be arrays so you can do something like:
$sql = 'SELECT ...';
# this array will contain all "AND" conditions
$pairs = [];
# loop over all your select groups
foreach ($_POST['field'] as $key => $field) {
if (!empty($field) && !empty($_POST['operator'][$key]) && !empty($_POST['value'][$key])) {
$pairs[] = $field . " " . $_POST['operator'][$key] . " '" . $_POST['value'][$key] . "'";
}
}
# add the conditions
if (count($pairs) > 0) {
$sql .= ' WHERE ' . implode(' AND ', $pairs);
}
# add sort order, execute sql, etc...
By the way, you should replace the value with a placeholder and use white-lists for the database-, table and column names and the operators to avoid sql injection / breaking your query.
来源:https://stackoverflow.com/questions/37807123/how-to-create-an-and-button-that-adds-a-and-statement-to-a-query