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

杀马特。学长 韩版系。学妹 提交于 2019-12-05 21:21:53

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.

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