我正在尝试使用复选框来筛选搜索结果。在SELECT
查询中,AND
和OR
都需要使用,具体取决于选中了多少个复选框和哪些复选框。这是HTML:
<table>
<tr>
<th>Filter Results</th>
</tr>
<tr>
<td>By chipset manufacturer:</td>
<td><input name="by_amd" id="amdF" type="checkbox" value="1" />AMD</td>
<td><input name="by_ati" id="atiF" type="checkbox" value="2" />ATI</td>
<td><input name="by_nvid" id="nvidiaF" type="checkbox" value="3" />nVidia</td>
</tr>
<tr>
<td>By year released:</td>
<td><input name="by_2014" id="2014F" type="checkbox" value="2014" />2014</td>
<td><input name="by_2013" id="2013F" type="checkbox" value="2013" />2013</td>
<td><input name="by_2012" id="2012F" type="checkbox" value="2012" />2012</td>
<td><input name="by_2011" id="2011F" type="checkbox" value="2011" />2011</td>
</tr>
</table>
和PHP:
// create base SELECT query
$select = 'SELECT GPUProductName, GPUChip, GPUReleaseDate, GPUBus, GPUMemory, GPUClock, GPUMemClock, GPUAddStats';
$from = ' FROM GPU';
$where = ' WHERE TRUE';
// create search filters
$opts = isset($_POST['filterOpts']) ? $_POST['filterOpts'] : array('');
// By chipset manufacturer
if (in_array("by_amd", $opts)){
$where .= " AND CMid = 1";
}
if (in_array("by_ati", $opts)){
$where .= " AND CMid = 2";
}
if (in_array("by_nvid", $opts)){
$where .= " AND CMid = 3";
}
// by release year
if (in_array("by_2014", $opts)){
$where .= " AND YEAR(GPUReleaseDate)='2014'";
}
// build complete SELECT query
$query = $select . $from . $where;
return $query;
如果选择"by ATI"answers"by AMD",SELECT语句应分别为WHERE CMid = 2 OR CMid = 1
。如果添加"到2014",SELECT语句应为WHERE YEAR(GPUReleaseYear) = 2014 AND CMid = 2 OR CMid = 1
。基本上,从同一类别(可以说)中挑选的过滤器应该用OR连接,从不同类别中挑选的滤波器应该用and连接。在PHP中,我如何根据从相同和/或不同类别中选中的复选框数量创建正确的SELECT语句?
$query = 'SELECT GPUProductName, GPUChip, GPUReleaseDate, GPUBus, GPUMemory, GPUClock, GPUMemClock, GPUAddStats FROM GPU WHERE ';
$manufacturers=array();
if(isset($_POST['by_amd']) $manufacturers[]="CMid=1";
if(isset($_POST['by_ati']) $manufacturers[]="CMid=2";
if(isset($_POST['by_nvid']) $manufacturers[]="CMid=3";
$query.='('.implode(' OR ',$manufacturers).')';
$query.=' AND ';
$years=array();
if(isset($_POST['by_2014']) $years[]="YEAR(GPUReleaseDate)=2014";
if(isset($_POST['by_2013']) $years[]="YEAR(GPUReleaseDate)=2013";
if(isset($_POST['by_2012']) $years[]="YEAR(GPUReleaseDate)=2012";
if(isset($_POST['by_2011']) $years[]="YEAR(GPUReleaseDate)=2011";
$query.='('.implode(' OR ',$years).')';
return $query;