我今天早上一直在使用mysql / php搜索表单,它使用复选框设置颜色参数。目前,通过get获取我的搜索条件,使用if语句来限定它们,将它们放入数组中,并使用AND来构建我的mysql查询。这项工作非常好,但是当我需要使用sql语句来使用if语句的多次迭代时,我遇到了问题。这是代码。我将在下面详细解释代码。
//Color
if (isset($_GET['white'])){
$white = $_GET['white'];
$where[] = "color = '".mysql_real_escape_string($white)."'";
}
if (isset($_GET['red'])){
$red = $_GET['red'];
$where[] = "color = '".mysql_real_escape_string($red)."'";
}
if (isset($_GET['blue'])){
$blue = $_GET['blue'];
$where[] = "color = '".mysql_real_escape_string($blue)."'";
}
if (isset($_GET['colorless'])){
$colorless = $_GET['colorless'];
$where[] = "color = '".mysql_real_escape_string($colorless)."'";
}
if (isset($_GET['green'])){
$green = $_GET['green'];
$where[] = "color = '".mysql_real_escape_string($green)."'";
}
if (isset($_GET['black'])){
$black = $_GET['black'];
$where[] = "color = '".mysql_real_escape_string($black)."'";
}
//GLUE ALL THE SEARCH FIELDS TOGETHER WITH AN IMPLODE STATEMENT
if(count($where)) {
$query.= 'SELECT * FROM inventory WHERE '.implode(' AND ', $where);
}
如您所见,例如,如果选中“white”复选框,我的mysql查询将显示为:
SELECT * FROM inventory WHERE color = 'W'
我遇到问题的地方如下。如果我需要使用多种颜色进行搜索,该怎么办?因此,例如在我的表单上,如果我同时检查WHITE和RED,我如何修改我的搜索,如下所示:
SELECT * FROM inventory WHERE color = 'WR'
任何帮助都将一如既往地受到赞赏。亲切的问候
酸杰克
答案 0 :(得分:3)
如何使用IN
?
$allowed = ['white', 'red', 'green', 'black'];
$found = [];
$clause = '';
foreach ($allowed as $a) {
if (isset($_GET[$a])) {
$found[] = mysql_real_escape_string($_GET[$a]);
}
}
$clause = '';
if (count($found)) {
$clause = sprintf(' WHERE color IN (%s)', implode(',', $found));
}
$query = 'SELECT * FROM inventory' . $clause;
答案 1 :(得分:0)
试试这个
//Color
if (isset($_GET['white'])){
$white = $_GET['white'];
$where[] = mysql_real_escape_string($white);
}
if (isset($_GET['red'])){
$red = $_GET['red'];
$where[] = mysql_real_escape_string($red);
}
if (isset($_GET['blue'])){
$blue = $_GET['blue'];
$where[] = mysql_real_escape_string($blue);
}
if (isset($_GET['colorless'])){
$colorless = $_GET['colorless'];
$where[] = mysql_real_escape_string($colorless);
}
if (isset($_GET['green'])){
$green = $_GET['green'];
$where[] = mysql_real_escape_string($green);
}
if (isset($_GET['black'])){
$black = $_GET['black'];
$where[] = mysql_real_escape_string($black);
}
if(count($where)) {
$query.= "SELECT * FROM inventory WHERE color IN ('".implode("','", $where)."')";
}