douyan2002 2019-04-22 18:34
浏览 497
已采纳

具有多个动态条件的SQL查询选择

I want to perform a SELECT query with conditions which are filled dynamically.

if($_POST['a']=='true'){
    $a = 'a,';
    $a_where = 'a >0';
}
if($_POST['b']=='true'){
    $b = 'b,';
    $b_where = 'b >0';
}
if($_POST['c']=='true'){
    $c = 'c,';
    $c_where = 'c >0';
}

Than i was tring to make WHERE

$where = 'WHERE '.$a_where.' OR '.$b_where.' OR '.$c_where;

And query

$query = mysql_query('SELECT id,'.$a.$b.$c.'date FROM t_name '.$where.' ORDER BY date DESC');

Problem is if b or a is not POST than i have error in query. Actualy only WHERE clause is problem here.

  • 写回答

1条回答 默认 最新

  • douyue7408 2019-04-22 18:41
    关注

    Rather than building the as separate variables, it's easier to collect them as arrays, do this for both the column names and the parts of the where clause and then use implode() to build the full SQL...

    $columns = [ 'id', 'date' ];
    $where = [];
    if($_POST['a']=='true'){
        $columns[] = 'a';
        $where[] = 'a >0';
    }
    if($_POST['b']=='true'){
        $columns[] = 'b';
        $where[] = 'b >0';
    }
    if($_POST['c']=='true'){
        $columns[] = 'c';
        $where[] = 'c >0';
    }
    
    $sql = 'SELECT '.implode(",", $columns).'
              FROM t_name 
              WHERE '.implode(" or ", $where).' 
              ORDER BY date DESC';
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 截图中的mathematics程序转换成matlab
  • ¥15 动力学代码报错,维度不匹配
  • ¥15 Power query添加列问题
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容
  • ¥15 关于#stm32#的问题:CANOpen的PDO同步传输问题