需求:根据省份,客户名称,通气时间这3个条件去排序,可以只选择一个,也可多个,这3个排序条件都是复选框,
sql 如下:
$MYSQL->query("select * from customer cu " .$where);
排序条件:
<input type="checkbox" name="sel_key10" />省份
<input type="checkbox" name="sel_key11" />客户名称
<input type="checkbox" name="sel_key12" />通气时间在 sql 后面拼接的排序条件if($sel_key10){
$where=$where." order by cu.province ";  // 省
}
if($sel_key11){
$where .= " ,cu.KFName";  // 客户名称
}
if($sel_key12){
$where .= " ,cu.GiveGasTime ";  // 通气时间 
}
 
我这样拼接的是有问题的,如果 单独以省作为排序条件是没有问题的,但是我单独以其他的作为条件,就不对了,如果我同时以2个,或3个,按照,省,客户名称,通气时间,这样的顺序也是对的,其实我要的sql 就是 :select * from customer cu where 1=1 order by cu.province,cu.KFName,cu.GiveGasTime ,如果没有条件就不要 order by ,有就在 括号里面追加。。
排序条件:省份 客户名称 通气时间 
sql拼接问题 ?

解决方案 »

  1.   

    可以这么写
    $where = array();
    if($sel_key10){
    $where[] =" cu.province ";  // 省
    }
    if($sel_key11){
    $where[] =" cu.KFName";  // 客户名称
    }
    if($sel_key12){
    $where[] = " cu.GiveGasTime ";  // 通气时间 
    }
    $MYSQL->query("select * from customer cu " . (!empty($where) ? 'order by '. implode(',',$where) : '');
      

  2.   

    测试代码<form method=post>
    <input type="checkbox" name="sel_key10" />省份
    <input type="checkbox" name="sel_key11" />客户名称
    <input type="checkbox" name="sel_key12" />通气时间
    <input type=submit>
    </form>
    <?php
    $dict = array(
      'sel_key10' => 'cu.province', // 省
      'sel_key11' => 'cu.KFName', // 客户名称
      'sel_key12' => 'cu.GiveGasTime', // 通气时间 
    );$sql = "select * from customer cu ";if($_POST) {
      $t = array_intersect_key($dict, $_POST);
      if($t) $sql .= 'order by ' . join(', ', $t);
    }
    echo $sql;
      

  3.   

    如果改造一下表单,处理起来更简单<form method=post>
    <input type="checkbox" name="o[]" value="cu.province" />省份
    <input type="checkbox" name="o[]" value="cu.KFName" />客户名称
    <input type="checkbox" name="o[]" value="cu.GiveGasTime" />通气时间
    <input type=submit>
    </form>
    <?php$sql = "select * from customer cu ";if(isset($_POST['o'])) {
      $sql .= 'order by ' . join(', ', $_POST['o']);
    }
    echo $sql;
      

  4.   

    容易产生sql注入漏洞,慎用