
image
例如為不定數(shù)量的查詢條件,我們?cè)诤笈_(tái)寫查詢的時(shí)候,類似于這樣的語句
$sql = "select * from table where";
當(dāng)條件starttime和endtime都為空時(shí)
if(starttime!=null){
$sql = $sql+" starttime="+$starttime;
}
if(endtime !=null){
$sql = $sql+"and endtime ="+$endtime;
}
這時(shí)我們的查詢語句就是 select * from table where starttime =2015-04-05 and endtime = 2015-04-07,查詢語句正確
但是如果條件都不滿足的話,語句就變成了 select * from table where ,這時(shí)候查詢就會(huì)報(bào)錯(cuò),
加上1=1的時(shí)候
$sql ="select * from table where 1=1",
if(starttime!=null){
$sql = $sql+" and starttime="+$starttime;
}
if($endtime !=null){
$sql = $sql+"and endtime ="+$endtime;
}
當(dāng)兩個(gè)條件成立的時(shí)候 select * from table where 1=1 and starttime =2015-04-05 and endtime = 2015-04-07, 語句正確
當(dāng)兩個(gè)條件不滿足時(shí) select * from table where 1=1 ,語句正確,會(huì)返回table表的所有數(shù)據(jù)