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

守給你的承諾、 提交于 2019-12-07 18:42:06

问题


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:


回答1:


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.



来源:https://stackoverflow.com/questions/37807123/how-to-create-an-and-button-that-adds-a-and-statement-to-a-query

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!