Home >Backend Development >PHP Tutorial > 多条件动态筛选,该如何处理

多条件动态筛选,该如何处理

WBOY
WBOYOriginal
2016-06-13 13:28:391492browse

多条件动态筛选
价格:1000 2000 3000
时间:2001 2002 2003
清除价格 清除时间 全部清除

现在点1000 已经有内容出来,不过MYSQL语句错误,再点一下2001,符合两个条件的内容也出来了,SQL没有提示错误。

$result=mysql_query('select * from news_c where title='.$title.' or f_id='.$f_id.'' );
现在要怎么样改sql才不会因为只点了一个条件而出错。

------解决方案--------------------
根据传入参数的数量,动态组装 sql 串
------解决方案--------------------
给你一个测试例

PHP code
$jg = array(1000, 2000, 3000);
$sj = array(2001, 2002, 2003);

if(isset($_GET['act'])) {
  $k = substr($_GET['act'], 3);
  unset($_GET['act']);
  if($k == 'all') $_GET = array();
  else unset($_GET[$k]);
}
  
echo '<br>价格:';
$param = getparam('jg');
foreach($jg as $v) echo " <a href="?%24param%24v">$v</a>";

echo '<br>时间:';
$param = getparam('sj');
foreach($sj as $v) echo " <a href="?%24param%24v">$v</a>";

$param = http_build_query($_GET);
echo "<p><a href="?act=deljg&%24param">清除价格</a> <a href="?act=delsj&%24param">清除时间</a> <a href="?act=delall&%24param">全部清除</a>";
echo "</p><p>select * from  tbl_name " . expr();

function getparam($k) {
  $param = $_GET;
  if(isset($_GET[$k])) unset($param[$k]);

  $param[$k] = '';
  return http_build_query($param);
}

function expr($expr='and') {
  if(! $_GET) return '';
  foreach($_GET as $k=>$v) $r[] = "$k='$v'";
  return 'where ' . join(" $expr ", $r);
} </p><div class="clear">
                 
              
              
        
            </div>
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn