示例: querystring = ?style=ranch&style=barn&style=colonial
php:
$sqlStyle = "SELECT DISTINCT COUNT(*) as count FROM houses_single ";
$i = 1;
foreach ($_GET as $key => $value) {
if ($i == 1){
$sqlStyle .= "where ";
}else{
$sqlStyle .= " and ";
}
$sqlStyle .= $key . " like '%" . $value ."%'";
$i++;
}
echo $sqlStyle;结果:选择DISTINCT COUNT(*)作为count FROM houses_single Where Houses‘%CLICATIONA%’
发布于 2013-03-03 08:41:47
在这种情况下,查询参数“key=value”是一个数组,必须用方括号标识-如果不是,最后一个样式对将覆盖其他样式对。
?style[]=ranch&style[]=barn&style[]=colonial$_GET['style']是一个数组,那么您可以使用foreach循环遍历
foreach ($_GET['style'] as $value) {
// ...
}如果'style‘不是您想要添加的唯一参数,您可以在foreach循环中使用is_array()检查:
foreach ($_GET as $key => $value) {
if ($i == 1){
$sqlStyle .= "where ";
}else{
$sqlStyle .= " and ";
}
if(is_array($value)) {
$sec = array();
foreach($value as $second_level) {
$sec[] = $key . " LIKE '%" . $second_level."%'";
}
$sqlStyle .= implode(' AND ', $sec);
}
else {
$sqlStyle .= $key . " LIKE '%" . $value ."%'";
}
$i++;
}
echo $sqlStyle;没有foreach的alternative:
<?php
$statement = "SELECT DISTINCT COUNT(*) as count FROM `houses_single`";
if(is_array($_GET)) {
$statement .= ' WHERE';
// create copy to keep the $_GET array
$add_where = $_GET;
array_walk(function($elem,$key){
is_array($elem) {
return implode(' AND ', array_map(function($sec) using ($key) {
return "$key LIKE '%$sec%'";
}, $elem);
}
else {
return "$key LIKE '%$elem%'";
}
},$add_where);
$statement .= implode(' AND ', $add_where);
}(代码未经测试)
Sidenode关于安全性:我希望您不会在没有任何参数转义的情况下在生产环境中使用您提供的代码片段。
https://stackoverflow.com/questions/15181131
复制相似问题