简体   繁体   English

通过选中具有自动更新的多个复选框来查询MySQL

[英]Query MySQL by checking multiple checkboxes with automatic update

I would like to build a kind of advanced mySQL search - with the help of JQuery - where the user query the database by checking checkboxes and as a checkbox is checked a DIV is immediately updated via AJAX with the results. 我想建立一种高级的mySQL搜索-在JQuery的帮助下-用户通过选中复选框来查询数据库,并且选中复选框后,DIV将立即通过AJAX更新结果。 A kind of autocomplete but with checkboxes. 一种自动完成功能,但带有复选框。

For example, I have two or more checkboxes as these: 例如,我有两个或多个复选框,如下所示:

<input type="checkbox" id="Windows" name="system"> Windows
<input type="checkbox" id="Linux" name="system"> Linux

If the user checks "Windows" mySQL does immediately (without clicking any Submit button) return a list of Windows softwares. 如果用户选中“ Windows”,则mySQL会立即执行操作(无需单击任何“提交”按钮),并返回Windows软件列表。 If the user checks both, mySQL should immediately return a list of Windows AND Linux softwares. 如果用户同时检查了两者,则mySQL应立即返回Windows和Linux软件的列表。

The following works fine for one choice but not for both: 以下对于一种选择有效,但对两种选择均无效:

<div id="update"></div>

$('input[name=system]').click(function(){
    var id=$(this).attr('id');
    $.get("review.php", {param: id}, 
        function(data) {
            $("div#update").html(data);
        }
    );
});

Review.php: Review.php:

if (isset($_GET['param'])) {
    $param = $_GET['param'];
}
$qry = mysql_query("SELECT * FROM reviews WHERE os = '".$param."' ") or die(mysql_error());

Thank you. 谢谢。

Try this: 尝试这个:

$('input[name=system]').click(function(){

    var ids = [];
    $('input[name=system]:checked').each(function() {
        ids.push($(this).attr('id'));
    });
    ids = ids.join(",");

    $.get("review.php", {param: ids}, 
        function(data) {
            $("div#update").html(data);
        }
    );
});

And in your PHP: 在您的PHP中:

if (isset($_GET['param'])) {
    $param = "('" . str_replace(",", "','", $_GET['param']) . "')";
}
$qry = mysql_query("SELECT * FROM reviews WHERE os IN $param") or die(mysql_error());

You need to create one click function for both check-boxes which would check both (all) values and create one http request such as ?param=windows,linux . 您需要为两个复选框创建一个单击功能,该功能将检查两个(所有)值并创建一个http请求,例如?param=windows,linux

You also need to update condition in mysql query, so it'd look like: 您还需要在mysql查询中更新条件,因此它看起来像:

$params = explode( ',', $param);
// escape all params (mysql_real_escape_string)
$condition = 'os IN("' . implode( '", "', $params) . '")';
$qry = mysql_query("SELECT * FROM reviews WHERE $condition") or die(mysql_error());

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

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