热搜:NVER node 开发 php

多个查询条件的sql语句的拼写技巧,求指点。

2024-09-21 18:20:01
多个查询条件的sql语句的拼写技巧,求指点。

多个查询条件的sql语句的拼写技巧,求指点。

$sql="select * from tb1";if($id=$_GET['id']){	$where.=" where id like "%$id%"";}if($name=$_GET['name']){	$where.=" where name like "%$name%"";}//当id有值的时候sql=select * from tb1 where id like "%$id%"//当name有值的时候sql=select * from tb1 where name like "%$name%"//当同时又值的时候,sql就出错了sql=select * from tb1 where name like "%$name%" where where id like "%$id%" //当然你可以说用if($id=$_GET['id']&&$name=$_GET['name']){	where.= "and";}

我举的例子只有两个条件,实际项目中我这里有十几个条件,这种方式肯定不行。
求更好的拼接方式


回复讨论(解决方案)

$where = array();foreach($_GET as $k=>v) $where[] = "$k like '%$v%'";$sql="select * from tb1";if($where) $sql .= ' where ' . join(' and ', $where);

$sql="select * from tb1";$where = array();if($id=$_GET['id']){    $where[]=" id like '%$id%'";}if($name=$_GET['name']){    $where[]=" name like '%$name%'";}$s=(!empty($where)) ? " where " . implode(" and " , $where) : '';$sql.=$s;

我个人觉得我这个简单

$sql="select * from tb1 where 1=1";if($id=$_GET['id']) $sql.=" and id like "%$id%"";if($name=$_GET['name']) $sql.=" and name like "%$name%"";

我个人觉得我这个简单

$sql="select * from tb1 where 1=1";if($id=$_GET['id']) $sql.=" and id like "%$id%"";if($name=$_GET['name']) $sql.=" and name like "%$name%"";

你这个只是直白  没2#的好啊  
但都是高手啊