使用多个值查询db for get-variable

时间:2015-01-18 13:15:40

标签: php mysql

我有代表产品状况的复选框。当用户检查示例Excellent时,值1存储在GET - 变量中,如下所示:

...index.php?condition=1

现在,当用户检查多个框(必须可以)时,它看起来像这样:

...index.php?condition=1,2,3

显然,我必须查询我的数据库才能显示与用户选择相对应的产品。

如果用户只检查一个框,则语句很简单:

if (!empty($_GET['condition'])){
$sql = $sql . " AND (Condition = '".$_GET['condition']."')";
} 

但是如果用户检查多个框怎么办?声明如何看? (甚至有可能以这种方式解决它吗?

谢谢!

这是创建地址的脚本:

<script>
$('#condition_select input:checkbox').change(function() {
var condition = $("#condition_select input:checkbox:checked").map(function() {
    return this.value;
}).get().join(',');
$("#submit_checkboxes").find("a").attr('href', 'index.php?condition=' + condition);
}).change();
</script>

HTML:

 <div class="mutliselect" id="condition_select">
 <form method="POST" action="">
 <ul>
  <li><input type="checkbox" id="d1" value="1"'; if(strpos($_GET['condition'],'1') !== false){ echo 'checked="checked"';} echo'/><label for="d1" class="checkbox_title">Neu</label></li>
<!-- and 6 more of these -->

有没有办法解决这个问题,而无需为每个复选框创建单独的GET - 变量?

1 个答案:

答案 0 :(得分:1)

更新(根据评论和问题更新再次更新):

问题已更新,所以我会更新我的答案。使用explode(http://php.net/manual/en/function.explode.php)来获取所有值,并使用implode来制定查询:

$values = explode(',', $_GET['condition']);
// VALIDATE each of values to match Your type.

if (!empty($values)) {

    // $values = [1, 2, 3]
    foreach ($values as $key => $value) {
        $values[$key] = '(condition = \''.$value.'\')';
    }
    // $values = ['(condition = \'1\')', '(condition = \'2\')', '(condition = \'3\')']
    $query = implode(' OR ', $values);
    // $query = '(condition = \'1\') OR (condition = \'2\') OR (condition = \'3\')', 
    $sql = $sql . ' AND ( '.$query.' )';
}

这是我认为的解决方案(MYSQL倍数AND:http://forums.mysql.com/read.php?10,250552)。爆炸工作示例:


$string = '1,2,3,4,asd,fgh';
$array = explode(',', $string);
print_r($array[0]); // 1
print_r($array[3]); // 4
print_r($array[5]); // 'fgh'  

这是编辑前的答案片段,但我认为值得留在这里:

Hoverwer,其中有许多安全漏洞!!!

您必须验证用户数据。如果有人传入地址,例如:

index.php?condition=; SHOW TABLES FROM database;

它可以潜在地显示一些数据。正如您所看到的,用户还可以使用delete statemant或INSERT INTO用户...等来进行寻址。

因此,在这种情况下,您应该切换到PDO(例如)http://php.net/manual/en/pdo.prepare.php,并制作准备好的语句。验证用户数据,如果您需要该号码,他只能传递号码。


您也可以使用isset:isset vs empty vs is_null。它不是必须的,但有时可能有用。对于每个表单,您还可以检查isset($ _POST [&#39;提交&#39;])尽可能多的垃圾邮件表单的机器人,有时只是省略提交按钮。它会减少我认为的请求数量。


请记住,使用POST和GET表单始终允许用户发送自己的POST / GET请求。在这种情况下,服务器端验证是必须的。


PS。对不起,大写字母,它们只是用来使它真正强大。验证用户数据;)。

最好的问候。