如何创建和按键,增加了A和语句的查询? [英] How to create an AND button that adds a AND statement to a query?

查看:135
本文介绍了如何创建和按键,增加了A和语句的查询?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在做某种类型的查询生成器的,我想实现一个按钮,一个AND语句添加到我的查询。我做了一个版本,在那里我有1和实施声明,但它是一个有点狡猾,我想用户所要做的不是一个,语句的更多的能力。这在code我的时刻。

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.

更新时间:这是我的.php文件:

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:

推荐答案

有几件事情:


  • 您当前的SQL会失败,如果第一对被清空因为不会有 WHERE 但只有条款

  • 在HTML中使用数组可以让你在PHP中使用数组,使得一切都轻松了很多通过循环在它来处理。

一个简单的例子:

HTML

<select name="field[]">...</select>
<select name="operator[]">...</select>
<select name="value[]">...</select>

您可以使用JavaScript来添加完全相同的code多对。

You can use javascript to add more pairs of the exact same code.

现在在PHP中的 $ _ POST 变量将是数组,所以你可以这样做:

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...

顺便说一句,你应该用一个占位符代替的价值和使用白名单的数据库 - ,表和列名和运营商,以避免SQL注入/破坏你的查询。

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.

这篇关于如何创建和按键,增加了A和语句的查询?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆