多個查詢條件的sql話語的拼字技巧,求指點

來源:互聯網
上載者:User
多個查詢條件的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";
  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

    如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

    A Free Trial That Lets You Build Big!

    Start building with 50+ products and up to 12 months usage for Elastic Compute Service

    • Sales Support

      1 on 1 presale consultation

    • After-Sales Support

      24/7 Technical Support 6 Free Tickets per Quarter Faster Response

    • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.