简体   繁体   English

如何在SQL查询中动态累积复选框值

[英]How to dynamically accumulate checkbox values in a SQL query

I have a search form where users can choose a few checkboxes, set a date range, use a wildcard search etc. and via button click it gets sent via ajax to a PHP file and executed in a MySQL query. 我有一个搜索表单,用户可以选择几个复选框,设置日期范围,使用通配符搜索等,然后通过单击按钮,将其通过ajax发送到PHP文件并在MySQL查询中执行。

In the php file I set up a cascade of if-statements to ensure the query works regardless of the user having chosen certain values, fe like this: 在php文件中,我设置了一系列if语句,以确保无论用户选择了某些值如何查询都可以执行,例如:

// variable from a risk level dropdown menu
if ($_POST['risklevelcount']=="") {
    $risklevel = "MASTER.RISK_LEVEL != ''";
}

else {
    $risklevel = "MASTER.RISK_LEVEL = "' . $risklevelcount . "'";
}

the variables then are implemented in the where clause of the mysql query, which looks like this: 然后,变量将在mysql查询的where子句中实现,如下所示:

$result = mysql_query("
SELECT *
FROM        MASTER
WHERE 
        (( ". $buttonvalue ." ) AND ( ". $date . " ) AND ( ". $risklevel ." ))
");

To ensure the query gets executed regardless of the user having checked a checkbox, I analoguously implemented them in a if-clause like this: 为了确保无论用户是否选中复选框,查询都将执行,我类似地在if子句中实现了它们,如下所示:

if(!empty($checkbox1)) 
    $checkbox1 = "MASTER_CHECK like '%dog%'"; 
else $checkbox1 = "MASTER.CHECK = '' OR MASTER.CHECK != ''";

if(!empty($checkbox2)) 
    $checkbox2 = "MASTER_CHECK like '%cat%'"; 
else $checkbox2 = "MASTER.CHECK = '' OR MASTER.CHECK != ''";

if(!empty($checkbox3)) 
    $checkbox3 = "MASTER_CHECK like '%bird%'"; 
else $checkbox3 = "MASTER.CHECK = '' OR MASTER.CHECK != ''";

If I add these to the above MySQL query where clause I obviously won't get the results I want: 如果将它们添加到上述MySQL查询where子句中,显然不会得到我想要的结果:

$result = mysql_query("SELECT *
FROM        MASTER
WHERE 
        (
            ( ". $buttonvalue ." ) AND ( ". $date . " ) AND (". risklevel .") AND
                (
                    (". $checkbox1.") OR (". $checkbox2.") OR (". $checkbox3.")
                )
        )
");

I won't get for example results for 'dog' AND 'cat' but not 'bird' (= checkbox 1 and 2 checked but not 3). 例如,我不会得到“狗”和“猫”的结果,但不会得到“鸟”的结果(=选中复选框1和2,但未选中3)。

I know this is a really stupid approach from the start, regardless of the checkboxes. 我知道这从一开始就是一个非常愚蠢的方法,而不考虑复选框。 I sadly don't know how to do any better yet. 可悲的是,我不知道该怎么做。 If someone could point me in the right direction, I would be very glad. 如果有人能指出我正确的方向,我将感到非常高兴。 I think there is a much more smart way to do it, fe with arrays? 我认为有更聪明的方法可以做到这一点,例如使用数组吗? I just really lack a real basis knowledge! 我真的真的没有一个基础知识!

I suppose you have a form like this one : 我想你有这样的一种形式:

<form id="myFormId" method="POST" action="index.php">
    <div>
        <label for="level">Level :</label>
        <select name="risklevelcount">
            <option value="">-- all level --</option>
            <option value="1">1</option>
            <option value="2">2</option>
            <option value="3">3</option>
        </select>
    </div>
    <div>
        <label>Any Pet ?</label>
        <input type="checkbox" name="pet[]" value="dog">dog
        <input type="checkbox" name="pet[]" value="cat">cat
        <input type="checkbox" name="pet[]" value="bird">bird
    </div>
    <input type="submit" value="submit">
</form>

Here is what I recommend for PHP part : 这是我推荐的PHP部分:

$strWhere = '1=1';

if(true === isset($_POST['risklevelcount']) && true === is_numeric($_POST['risklevelcount']))
{
    $strWhere = ' AND MATER.RISK_LEVEL = '.mysql_escape_string($_POST['risklevelcount']);
}

if(true === isset($_POST['pet']) && 0 < sizeof($_POST['pet']))
{
    $strWhere .= 'AND (';
    foreach($_POST['pet'] as $pet)
    {
        $strWhere .= ' MASTER_CHECK like "%'.mysql_escape_string($pet).'%" OR ';
    }
    //remove last OR
    $strWhere = substring($strWhere, 0, -3);
    $strWhere .= ')';
}

$result = mysql_query("SELECT * FROM MASTER WHERE ".$strWhere);

I agree with mate, use mysqli or PDO is better, at least escape strings. 我同意队友,使用mysqliPDO更好,至少转义字符串。 Moreover, stop saying in your queries MASTER.RISK_LEVEL != '' or worst MASTER.CHECK = '' OR MASTER.CHECK != '' . 此外,不要在查询中说MASTER.RISK_LEVEL != ''或最差的MASTER.CHECK = '' OR MASTER.CHECK != ''

In the first case, I supposed risk_level is always defined. 在第一种情况下,我认为总是定义risk_level。 So no need to say risk_level != '' . 因此无需说risk_level != '' And in the second case, Its useless to say I want string null or not null. 在第二种情况下,说我想要字符串为null或不为null毫无用处。 Just dont ask and you 'll have all results. 只是不要问,您将获得所有结果。

EDIT : 编辑:

If you check the form at the beginning of my answer, I've add an ID which is myFormId . 如果您在回答的开头检查表单,则我添加了一个ID,即myFormId So with jQuery, if you want to serialize your form data, just do : 因此,使用jQuery,如果要序列化表单数据,只需执行以下操作:

javascript: javascript:

var formData = $('#myFormId').serialize();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM