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);
?>
And here is a image of what it should look like:

A few things:
WHERE but only AND clauses.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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With