Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create an AND button that adds a AND statement to a query?

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: click here

like image 369
L.fcg Avatar asked Nov 20 '25 19:11

L.fcg


1 Answers

A few things:

  • Your current sql will fail if the first pair is emptied as there will be no WHERE but only AND 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.

like image 78
jeroen Avatar answered Nov 22 '25 07:11

jeroen



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!