CI對資料庫句的操作有時很方便有時卻讓人為難,例如括弧的問題。括弧的問題來自於處理and和or的優先順序關係。
有時需要or高於and。$this->db->where()和$this->db->orwhere()要如何做到呢。
第一種:自己寫sql語句。可是有時候已經寫好的程式要這樣改動很難。
第二種:自己寫where語句,有可能會遇到這樣的問題。
where()和orwhere()其實是雷同的函數。
手冊中有這樣一段:
$this->db->where();
本函數允許你使用四種方法中的一種來設定 WHERE 子句:
說明: 傳遞給本函數的所有值都會被自動轉義,以便產生安全的查詢。
簡單的 key/value 方法: $this->db->where('name', $name);
// 產生: WHERE name = 'Joe'
請注意等號已經為你添加。
如果你多次調用本函數,那麼這些條件會被 AND 串連起來:
$this->db->where('name', $name);
$this->db->where('title', $title);
$this->db->where('status', $status);
// WHERE name = 'Joe' AND title = 'boss' AND status = 'active' 自訂 key/value 方法:
你可以在第一個參數中包含一個運算子,以便控制比較:
$this->db->where('name !=', $name);
$this->db->where('id <', $id);
// 產生: WHERE name != 'Joe' AND id < 45 關聯陣列方法: $array = array('name' => $name, 'title' => $title, 'status' => $status);
$this->db->where($array);
// 產生: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'
使用這個方法時你也可以包含運算子:
$array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);
$this->db->where($array); 自訂字串:
你可以手動的編寫子句:
$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);
$this->db->where() 接受可選的第三個參數。如果你將它設定為 FALSE, CodeIgniter 將不會為你那些包含反勾號的欄位名或表名提供保護。
$this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);
標紅的地方很重要,第4所說的:
$where = "name='Joe' AND status='boss' OR status='active'";
$this->db->where($where);
其實是行不通的。where()會給語句加上``,然後說:
"`name='Joe' AND status='boss' OR status='active'`"sql語句有錯。
第三種:
改原始碼:
CI論壇裡有這樣一段:
... ...
給like數組加上括弧即可。
修改system\database\DB_active_rec.php
約第1559行
PHP
if ( count ( $this -> ar_like ) > 0 )
{
if ( count ( $this -> ar_where ) > 0 )
{
$sql .= "nAND " ;
}
$sql .= implode ( "n" , $this -> ar_like ) ;
}
改為
PHP
if ( count ( $this -> ar_like ) > 0 )
{
if ( count ( $this -> ar_where ) > 0 )
{
$sql .= "nAND (" ;
}
$sql .= implode ( "n" , $this -> ar_like ) ;
if ( count ( $this -> ar_where ) > 0 )
{
$sql .= ")" ;
}
}
希望CI開發人員儘快修補or_like無法內部形成括弧的BUG
這個論壇很腦殘,顯示斷行符號符\n會掉一個斜杠,懂PHP的自己加上。
源自:http://codeigniter.org.cn/forums/thread-1270-1-1.html
同理,可以對where修改,但是這種只是對where語句的開始和末尾加。
對於實際的需要,幾種合起來用基本情況都能解決了。不知道是不是還有更好的。呵呵,那應該就是直接修複CI原始碼內部形成括弧的BUG了吧