使用复选框和内爆阵列构建Mysql查询

时间:2015-06-07 19:35:01

标签: php mysql

我尝试使用搜索来构建一个mysql查询,利用复选框,下拉菜单等。下拉菜单和文本字段工作正常,因为它们只能解决列中可能存在的一个值,但复选框变得棘手他们开始复制数据。例如,这是我目前拥有的代码。

$where = array();
if(isset($_GET['cardname'])){
    if($_GET['cardname']==''){
    $card_name = mysql_real_escape_string($_GET['cardname']);
    } else{
    $card_name = mysql_real_escape_string($_GET['cardname']);
    $where[] = "card_name = '".mysql_real_escape_string($card_name)."'";
    }
}

if (isset($_GET['card_set'])){
    if($_GET['card_set']==''){

    } else {
    $set_name = $_GET['card_set'];
    $where[] = "card_set = '".mysql_real_escape_string($set_name)."'";
    }
}

//Rarity

if (isset($_GET['mythic'])){
    $mythic = $_GET['mythic'];
    $where[] = "rarity IN = '".mysql_real_escape_string($mythic);
    }

if (isset($_GET['rare'])){
    $rare = $_GET['rare'];
    $where[] ="rarity IN = '". mysql_real_escape_string($rare);
}

if(count($where)) {
    $query.= 'SELECT * FROM inventory WHERE '.implode(' AND ', $where);
}

我正在尝试构建如下的查询:

SELECT * FROM inventory WHERE card_name = '$card_name' AND '$card_set' = $card_set AND rarity IN = 'r','u';

你会在sql语句中注意到' rarity in'正在检查R和U这两个值。我遇到的问题是我无法在不写“稀有”的情况下弄清楚如何破坏我的阵列。每次选中一个复选框时都到sql语句。当我运行我的代码并检查两个复选框时,我得到了这个:

SELECT * FROM inventory WHERE card_name = 'Black ' AND card_set = '4E' AND rarity = ('M') AND rarity = ('R')

而我真正需要的是这个

SELECT * FROM inventory WHERE card_name = 'Black ' AND card_set = '4E' AND rarity = ('M','R')

任何帮助都将不胜感激。

亲切的问候 酸杰克

1 个答案:

答案 0 :(得分:1)

您需要将这些复选框存储在不同的数组中,然后一次性使用它们

IN不使用=,它写为“列IN(val,val)”

//Rarity

$whereIn = array();
if (isset($_GET['mythic'])){
    $mythic = $_GET['mythic'];
    $whereIn[] = mysql_real_escape_string($mythic);
    }

if (isset($_GET['rare'])){
    $rare = $_GET['rare'];
    $whereIn[] = mysql_real_escape_string($rare);
}
if(!empty($whereIn)) {
    $where[] ="rarity IN ( '". implode("','", $whereIn) . "')'";
}