gpt4 book ai didi

PHP、AJAX、MySQL 的复选框过滤以及 AND/OR 之间的切换

转载 作者:行者123 更新时间:2023-11-29 07:50:27 24 4
gpt4 key购买 nike

我正在尝试使用复选框来过滤搜索结果。在 SELECT 查询中,需要使用 ANDOR,具体取决于选中的复选框数量和复选框。这是 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”和“by AMD”,则 SELECT 语句应分别为 WHERE CMid = 2 OR CMid = 1。如果您随后添加“by 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;

关于PHP、AJAX、MySQL 的复选框过滤以及 AND/OR 之间的切换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26574791/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com