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 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记