CodeIgniter php sql

來源:互聯網
上載者:User
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了吧

  • 聯繫我們

    該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.