Spelling skills of SQL statements with multiple query conditions. Spelling skills of SQL statements with multiple query conditions. $ Sqlselect & nbsp; * & nbsp; from & nbsp; tb1; if ($ id]) {$ where. & nbsp; where & nbsp; id & nbsp; like & nbsp; % $ id % ;} if ($ name $ _ GET [spelling skills of SQL statements with multiple query conditions in nam.
Spelling skills of SQL statements with multiple query conditions.
$ SQL = "select * from tb1 ";
If ($ id = $ _ GET ['id'])
{
$ Where. = "where id like" % $ id % "";
}
If ($ name = $ _ GET ['name'])
{
$ Where. = "where name like" % $ name % "";
}
// When the id has a value
SQL = select * from tb1 where id like "% $ id %"
// When the name has a value
SQL = select * from tb1 where name like "% $ name %"
// When both values are returned, an error occurs in the SQL statement.
SQL = select * from tb1 where name like "% $ name %" where id like "% $ id %"
// Of course you can use
If ($ id = $ _ GET ['id'] & $ name = $ _ GET ['name'])
{
Where. = "and ";
}
In my example, there are only two conditions. in actual projects, I have more than a dozen conditions. this method is definitely not feasible.
Better splicing method
Share:
------ Solution --------------------
$where = array();
foreach($_GET as $k=>v) $where[] = "$k like '%$v%'";
$sql="select * from tb1";
if($where) $sql .= ' where ' . join(' and ', $where);
------ Solution --------------------
$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;
------ Solution --------------------
I personally think this is simple.
$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%"";
------ Solution --------------------
Reference:
I personally think this is simple.
$sql="select * from tb1 where 1=1";