当前位置:Gxlcms > PHP教程 > sql拼接的有关问题?

sql拼接的有关问题?

时间:2021-07-01 10:21:17 帮助过:6人阅读

求一个 sql 拼接的问题 ??
需求:根据省份,客户名称,通气时间这3个条件去排序,可以只选择一个,也可多个,这3个排序条件都是复选框,
sql 如下:
$MYSQL->query("select * from customer cu " .$where);


排序条件:
省份
客户名称
通气时间

在 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 拼接问题??

分享到:


------解决方案--------------------
可以这么写
$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) : '');

------解决方案--------------------
测试代码

$dict = array(
'sel_key10' => 'cu.province', // 省
'sel_key11' => 'cu.KFName', // 客户名称
'sel_key12' => 'cu.GiveGasTime', // 通气时间

人气教程排行