CodeIgniter 查詢構(gòu)造器類

2018-07-21 15:41 更新

查詢構(gòu)造器類

CodeIgniter 提供了查詢構(gòu)造器類,查詢構(gòu)造器允許你使用較少的代碼來在數(shù)據(jù)庫中 獲取、新增或更新數(shù)據(jù)。有時只需要一兩行代碼就能完成數(shù)據(jù)庫操作。CodeIgniter 并不需要為每個數(shù)據(jù)表提供一個類,而是使用了一種更簡單的接口。

除了簡單,使用查詢構(gòu)造器的另一個好處是可以讓你創(chuàng)建數(shù)據(jù)庫獨(dú)立的應(yīng)用程序, 這是因為查詢語句是由每個獨(dú)立的數(shù)據(jù)庫適配器生成的。另外,由于系統(tǒng)會自動對數(shù)據(jù) 進(jìn)行轉(zhuǎn)義,所以它還能提供更安全的查詢。

注解

如果你想要編寫你自己的查詢語句,你可以在數(shù)據(jù)庫配置文件中禁用這個類, 這樣數(shù)據(jù)庫核心類庫和適配器將使用更少的資源。

查詢

下面的方法用來構(gòu)建 SELECT 語句。

$this->db->get()

該方法執(zhí)行 SELECT 語句并返回查詢結(jié)果,可以得到一個表的所有數(shù)據(jù):

$query = $this->db->get('mytable');  // Produces: SELECT * FROM mytable

第二和第三個參數(shù)用于設(shè)置 LIMIT 子句:

$query = $this->db->get('mytable', 10, 20);

// Executes: SELECT * FROM mytable LIMIT 20, 10
// (in MySQL. Other databases have slightly different syntax)

你應(yīng)該已經(jīng)注意到了,上面的方法的結(jié)果都賦值給了一個 $query 變量,通過這個變量, 我們可以得到查詢的結(jié)果:

$query = $this->db->get('mytable');

foreach ($query->result() as $row)
{
    echo $row->title;
}

參考 生成查詢結(jié)果 頁面獲取關(guān)于生成結(jié)果的更多信息。

$this->db->get_compiled_select()

該方法和 $this->db->get() 方法一樣編譯 SELECT 查詢并返回查詢的 SQL 語句, 但是,該方法并不執(zhí)行它。

例子:

$sql = $this->db->get_compiled_select('mytable');
echo $sql;

// Prints string: SELECT * FROM mytable

第二個參數(shù)用于設(shè)置是否重置查詢(默認(rèn)會重置,和使用 $this->db->get() 方法時一樣):

echo $this->db->limit(10,20)->get_compiled_select('mytable', FALSE);

// Prints string: SELECT * FROM mytable LIMIT 20, 10
// (in MySQL. Other databases have slightly different syntax)

echo $this->db->select('title, content, date')->get_compiled_select();

// Prints string: SELECT title, content, date FROM mytable LIMIT 20, 10

上面的例子中,最值得注意的是,第二個查詢并沒有用到 $this->db->from() 方法, 也沒有為查詢指定表名參數(shù),但是它生成的 SQL 語句中有 FROM mytable 子句。 這是因為查詢并沒有被重置(使用 $this->db->get() 方法查詢會被執(zhí)行并被重置, 使用 $this->db->reset_query() 方法直接重置)。

$this->db->get_where()

這個方法基本上和上面的方法一樣,但它提供了第二個參數(shù)可以讓你添加一個 WHERE 子句, 而不是使用 db->where() 方法:

$query = $this->db->get_where('mytable', array('id' => $id), $limit, $offset);

閱讀下面的 db->where() 方法獲取更多信息。

注解

get_where() 方法的前身為 getwhere(), 已廢除

$this->db->select()

該方法用于編寫查詢語句中的 SELECT 子句:

$this->db->select('title, content, date');
$query = $this->db->get('mytable');

// Executes: SELECT title, content, date FROM mytable

注解

如果你要查詢表的所有列,可以不用寫這個函數(shù),CodeIgniter 會自動查詢所有列(SELECT *)。

$this->db->select() 方法的第二個參數(shù)可選,如果設(shè)置為 FALSE,CodeIgniter 將不保護(hù)你的 表名和字段名,這在當(dāng)你編寫復(fù)合查詢語句時很有用,不會破壞你編寫的語句。

$this->db->select('(SELECT SUM(payments.amount) FROM payments WHERE payments.invoice_id=4') AS amount_paid', FALSE);
$query = $this->db->get('mytable');

$this->db->select_max()

該方法用于編寫查詢語句中的 SELECT MAX(field) 部分,你可以使用第二個參數(shù)(可選)重命名結(jié)果字段。

$this->db->select_max('age');
$query = $this->db->get('members');  // Produces: SELECT MAX(age) as age FROM members

$this->db->select_max('age', 'member_age');
$query = $this->db->get('members'); // Produces: SELECT MAX(age) as member_age FROM members

$this->db->select_min()

該方法用于編寫查詢語句中的 SELECT MIN(field) 部分,和 select_max() 方法一樣, 你可以使用第二個參數(shù)(可選)重命名結(jié)果字段。

$this->db->select_min('age');
$query = $this->db->get('members'); // Produces: SELECT MIN(age) as age FROM members

$this->db->select_avg()

該方法用于編寫查詢語句中的 SELECT AVG(field) 部分,和 select_max() 方法一樣, 你可以使用第二個參數(shù)(可選)重命名結(jié)果字段。

$this->db->select_avg('age');
$query = $this->db->get('members'); // Produces: SELECT AVG(age) as age FROM members

$this->db->select_sum()

該方法用于編寫查詢語句中的 SELECT SUM(field) 部分,和 select_max() 方法一樣, 你可以使用第二個參數(shù)(可選)重命名結(jié)果字段。

$this->db->select_sum('age');
$query = $this->db->get('members'); // Produces: SELECT SUM(age) as age FROM members

$this->db->from()

該方法用于編寫查詢語句中的 FROM 子句:

$this->db->select('title, content, date');
$this->db->from('mytable');
$query = $this->db->get();  // Produces: SELECT title, content, date FROM mytable

注解

正如前面所說,查詢中的 FROM 部分可以在方法 $this->db->get() 中指定,所以,你可以 選擇任意一種你喜歡的方式。

$this->db->join()

該方法用于編寫查詢語句中的 JOIN 子句:

$this->db->select('*');
$this->db->from('blogs');
$this->db->join('comments', 'comments.id = blogs.id');
$query = $this->db->get();

// Produces:
// SELECT * FROM blogs JOIN comments ON comments.id = blogs.id

如果你的查詢中有多個連接,你可以多次調(diào)用這個方法。

你可以傳入第三個參數(shù)指定連接的類型,有這樣幾種選擇:left,right,outer,inner,left outer 和 right outer 。

$this->db->join('comments', 'comments.id = blogs.id', 'left');
// Produces: LEFT JOIN comments ON comments.id = blogs.id

搜索

$this->db->where()

該方法提供了4中方式讓你編寫查詢語句中的 WHERE 子句:

注解

所有的數(shù)據(jù)將會自動轉(zhuǎn)義,生成安全的查詢語句。

  1. 簡單的 key/value 方式:

    $this->db->where('name', $name); // Produces: WHERE name = 'Joe'

    注意自動為你加上了等號。

    如果你多次調(diào)用該方法,那么多個 WHERE 條件將會使用 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'
  2. 自定義 key/value 方式:

    為了控制比較,你可以在第一個參數(shù)中包含一個比較運(yùn)算符:

    $this->db->where('name !=', $name);
    $this->db->where('id <', $id); // Produces: WHERE name != 'Joe' AND id < 45
  3. 關(guān)聯(lián)數(shù)組方式:

    $array = array('name' => $name, 'title' => $title, 'status' => $status);
    $this->db->where($array);
    // Produces: WHERE name = 'Joe' AND title = 'boss' AND status = 'active'

    你也可以在這個方法里包含你自己的比較運(yùn)算符:

    $array = array('name !=' => $name, 'id <' => $id, 'date >' => $date);
    $this->db->where($array);
  4. 自定義字符串:

    你可以完全手工編寫 WHERE 子句:

    $where = "name='Joe' AND status='boss' OR status='active'";
    $this->db->where($where);

$this->db->where() 方法有一個可選的第三個參數(shù),如果設(shè)置為 FALSE,CodeIgniter 將不保護(hù)你的表名和字段名。

$this->db->where('MATCH (field) AGAINST ("value")', NULL, FALSE);

$this->db->or_where()

這個方法和上面的方法一樣,只是多個 WHERE 條件之間使用 OR 進(jìn)行連接:

$this->db->where('name !=', $name);
$this->db->or_where('id >', $id);  // Produces: WHERE name != 'Joe' OR id > 50

注解

or_where() 方法的前身為 orwhere(), 已廢除

$this->db->where_in()

該方法用于生成 WHERE IN 子句,多個子句之間使用 AND 連接

$names = array('Frank', 'Todd', 'James');
$this->db->where_in('username', $names);
// Produces: WHERE username IN ('Frank', 'Todd', 'James')

$this->db->or_where_in()

該方法用于生成 WHERE IN 子句,多個子句之間使用 OR 連接

$names = array('Frank', 'Todd', 'James');
$this->db->or_where_in('username', $names);
// Produces: OR username IN ('Frank', 'Todd', 'James')

$this->db->where_not_in()

該方法用于生成 WHERE NOT IN 子句,多個子句之間使用 AND 連接

$names = array('Frank', 'Todd', 'James');
$this->db->where_not_in('username', $names);
// Produces: WHERE username NOT IN ('Frank', 'Todd', 'James')

$this->db->or_where_not_in()

該方法用于生成 WHERE NOT IN 子句,多個子句之間使用 OR 連接

$names = array('Frank', 'Todd', 'James');
$this->db->or_where_not_in('username', $names);
// Produces: OR username NOT IN ('Frank', 'Todd', 'James')

模糊搜索

$this->db->like()

該方法用于生成 LIKE 子句,在進(jìn)行搜索時非常有用。

注解

所有數(shù)據(jù)將會自動被轉(zhuǎn)義。

  1. 簡單 key/value 方式:

    $this->db->like('title', 'match');
    // Produces: WHERE `title` LIKE '%match%' ESCAPE '!'

    如果你多次調(diào)用該方法,那么多個 WHERE 條件將會使用 AND 連接起來:

    $this->db->like('title', 'match');
    $this->db->like('body', 'match');
    // WHERE `title` LIKE '%match%' ESCAPE '!' AND  `body` LIKE '%match% ESCAPE '!'

    可以傳入第三個可選的參數(shù)來控制 LIKE 通配符(%)的位置,可用選項有:'before','after' 和 'both' (默認(rèn)為 'both')。

    $this->db->like('title', 'match', 'before');    // Produces: WHERE `title` LIKE '%match' ESCAPE '!'
    $this->db->like('title', 'match', 'after'); // Produces: WHERE `title` LIKE 'match%' ESCAPE '!'
    $this->db->like('title', 'match', 'both');  // Produces: WHERE `title` LIKE '%match%' ESCAPE '!'
  2. 關(guān)聯(lián)數(shù)組方式:

    $array = array('title' => $match, 'page1' => $match, 'page2' => $match);
    $this->db->like($array);
    // WHERE `title` LIKE '%match%' ESCAPE '!' AND  `page1` LIKE '%match%' ESCAPE '!' AND  `page2` LIKE '%match%' ESCAPE '!'

$this->db->or_like()

這個方法和上面的方法一樣,只是多個 WHERE 條件之間使用 OR 進(jìn)行連接:

$this->db->like('title', 'match'); $this->db->or_like('body', $match);
// WHERE `title` LIKE '%match%' ESCAPE '!' OR  `body` LIKE '%match%' ESCAPE '!'

注解

or_like() 方法的前身為 orlike(), 已廢除

$this->db->not_like()

這個方法和 like() 方法一樣,只是生成 NOT LIKE 子句:

$this->db->not_like('title', 'match');  // WHERE `title` NOT LIKE '%match% ESCAPE '!'

$this->db->or_not_like()

這個方法和 not_like() 方法一樣,只是多個 WHERE 條件之間使用 OR 進(jìn)行連接:

$this->db->like('title', 'match');
$this->db->or_not_like('body', 'match');
// WHERE `title` LIKE '%match% OR  `body` NOT LIKE '%match%' ESCAPE '!'

$this->db->group_by()

該方法用于生成 GROUP BY 子句:

$this->db->group_by("title"); // Produces: GROUP BY title

你也可以通過一個數(shù)組傳入多個值:

$this->db->group_by(array("title", "date"));  // Produces: GROUP BY title, date

注解

group_by() 方法前身為 groupby(), 已廢除

$this->db->distinct()

該方法用于向查詢中添加 DISTINCT 關(guān)鍵字:

$this->db->distinct();
$this->db->get('table'); // Produces: SELECT DISTINCT * FROM table

$this->db->having()

該方法用于生成 HAVING 子句,有下面兩種不同的語法:

$this->db->having('user_id = 45');  // Produces: HAVING user_id = 45
$this->db->having('user_id',  45);  // Produces: HAVING user_id = 45

你也可以通過一個數(shù)組傳入多個值:

$this->db->having(array('title =' => 'My Title', 'id <' => $id));
// Produces: HAVING title = 'My Title', id < 45

如果 CodeIgniter 自動轉(zhuǎn)義你的查詢,為了避免轉(zhuǎn)義,你可以將第三個參數(shù)設(shè)置為 FALSE 。

$this->db->having('user_id',  45);  // Produces: HAVING `user_id` = 45 in some databases such as MySQL
$this->db->having('user_id',  45, FALSE);  // Produces: HAVING user_id = 45

$this->db->or_having()

該方法和 having() 方法一樣,只是多個條件之間使用 OR 進(jìn)行連接。

排序

$this->db->order_by()

該方法用于生成 ORDER BY 子句。

第一個參數(shù)為你想要排序的字段名,第二個參數(shù)用于設(shè)置排序的方向, 可選項有: ASC(升序),DESC(降序)和 RANDOM (隨機(jī))。

$this->db->order_by('title', 'DESC');
// Produces: ORDER BY `title` DESC

第一個參數(shù)也可以是你自己的排序字符串:

$this->db->order_by('title DESC, name ASC');
// Produces: ORDER BY `title` DESC, `name` ASC

如果需要根據(jù)多個字段進(jìn)行排序,可以多次調(diào)用該方法。

$this->db->order_by('title', 'DESC');
$this->db->order_by('name', 'ASC');
// Produces: ORDER BY `title` DESC, `name` ASC

如果你選擇了 RANDOM (隨機(jī)排序),第一個參數(shù)會被忽略,但是你可以傳入一個 數(shù)字值,作為隨機(jī)數(shù)的 seed。

$this->db->order_by('title', 'RANDOM');
// Produces: ORDER BY RAND()

$this->db->order_by(42, 'RANDOM');
// Produces: ORDER BY RAND(42)

注解

order_by() 方法的前身為 orderby(), 已廢除

注解

Oracle 暫時還不支持隨機(jī)排序,會默認(rèn)使用升序

分頁與計數(shù)

$this->db->limit()

該方法用于限制你的查詢返回結(jié)果的數(shù)量:

$this->db->limit(10);  // Produces: LIMIT 10

第二個參數(shù)可以用來設(shè)置偏移。

// Produces: LIMIT 20, 10 (in MySQL.  Other databases have slightly different syntax)
$this->db->limit(10, 20);

$this->db->count_all_results()

該方法用于獲取特定查詢返回結(jié)果的數(shù)量,也可以使用查詢構(gòu)造器的這些方法: where(),or_where(),like(),or_like() 等等。舉例:

echo $this->db->count_all_results('my_table');  // Produces an integer, like 25
$this->db->like('title', 'match');
$this->db->from('my_table');
echo $this->db->count_all_results(); // Produces an integer, like 17

但是,這個方法會重置你在 select() 方法里設(shè)置的所有值,如果你希望保留它們,可以將 第二個參數(shù)設(shè)置為 FALSE

echo $this->db->count_all_results('my_table', FALSE);

$this->db->count_all()

該方法用于獲取某個表的總行數(shù),第一個參數(shù)為表名:

echo $this->db->count_all('my_table');  // Produces an integer, like 25

查詢條件組

查詢條件組可以讓你生成用括號括起來的一組 WHERE 條件,這能創(chuàng)造出非常復(fù)雜的 WHERE 子句, 支持嵌套的條件組。例如:

$this->db->select('*')->from('my_table')
    ->group_start()
        ->where('a', 'a')
        ->or_group_start()
            ->where('b', 'b')
            ->where('c', 'c')
        ->group_end()
    ->group_end()
    ->where('d', 'd')
->get();

// Generates:
// SELECT * FROM (`my_table`) WHERE ( `a` = 'a' OR ( `b` = 'b' AND `c` = 'c' ) ) AND `d` = 'd'

注解

條件組必須要配對,確保每個 group_start() 方法都有一個 group_end() 方法與之配對。

$this->db->group_start()

開始一個新的條件組,為查詢中的 WHERE 條件添加一個左括號。

$this->db->or_group_start()

開始一個新的條件組,為查詢中的 WHERE 條件添加一個左括號,并在前面加上 OR 。

$this->db->not_group_start()

開始一個新的條件組,為查詢中的 WHERE 條件添加一個左括號,并在前面加上 NOT 。

$this->db->or_not_group_start()

開始一個新的條件組,為查詢中的 WHERE 條件添加一個左括號,并在前面加上 OR NOT 。

$this->db->group_end()

結(jié)束當(dāng)前的條件組,為查詢中的 WHERE 條件添加一個右括號。

插入數(shù)據(jù)

$this->db->insert()

該方法根據(jù)你提供的數(shù)據(jù)生成一條 INSERT 語句并執(zhí)行,它的參數(shù)是一個數(shù)組 或一個對象,下面是使用數(shù)組的例子:

$data = array(
    'title' => 'My title',
    'name' => 'My Name',
    'date' => 'My date'
);

$this->db->insert('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')

第一個參數(shù)為要插入的表名,第二個參數(shù)為要插入的數(shù)據(jù),是個關(guān)聯(lián)數(shù)組。

下面是使用對象的例子:

/*
class Myclass {
    public $title = 'My Title';
    public $content = 'My Content';
    public $date = 'My Date';
}
*/

$object = new Myclass;
$this->db->insert('mytable', $object);
// Produces: INSERT INTO mytable (title, content, date) VALUES ('My Title', 'My Content', 'My Date')

第一個參數(shù)為要插入的表名,第二個參數(shù)為要插入的數(shù)據(jù),是個對象。

注解

所有數(shù)據(jù)會被自動轉(zhuǎn)義,生成安全的查詢語句。

$this->db->get_compiled_insert()

該方法和 $this->db->insert() 方法一樣根據(jù)你提供的數(shù)據(jù)生成一條 INSERT 語句,但是并不執(zhí)行。

例如:

$data = array(
    'title' => 'My title',
    'name'  => 'My Name',
    'date'  => 'My date'
);

$sql = $this->db->set($data)->get_compiled_insert('mytable');
echo $sql;

// Produces string: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')

第二個參數(shù)用于設(shè)置是否重置查詢(默認(rèn)情況下會重置,正如 $this->db->insert() 方法一樣):

echo $this->db->set('title', 'My Title')->get_compiled_insert('mytable', FALSE);

// Produces string: INSERT INTO mytable (title) VALUES ('My Title')

echo $this->db->set('content', 'My Content')->get_compiled_insert();

// Produces string: INSERT INTO mytable (title, content) VALUES ('My Title', 'My Content')

上面的例子中,最值得注意的是,第二個查詢并沒有用到 $this->db->from() 方法, 也沒有為查詢指定表名參數(shù),但是它生成的 SQL 語句中有 INTO mytable 子句。 這是因為查詢并沒有被重置(使用 $this->db->insert() 方法會被執(zhí)行并被重置, 使用 $this->db->reset_query() 方法直接重置)。

注解

這個方法不支持批量插入。

$this->db->insert_batch()

該方法根據(jù)你提供的數(shù)據(jù)生成一條 INSERT 語句并執(zhí)行,它的參數(shù)是一個數(shù)組 或一個對象,下面是使用數(shù)組的例子:

$data = array(
    array(
        'title' => 'My title',
        'name' => 'My Name',
        'date' => 'My date'
    ),
    array(
        'title' => 'Another title',
        'name' => 'Another Name',
        'date' => 'Another date'
    )
);

$this->db->insert_batch('mytable', $data);
// Produces: INSERT INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date'),  ('Another title', 'Another name', 'Another date')

第一個參數(shù)為要插入的表名,第二個參數(shù)為要插入的數(shù)據(jù),是個二維數(shù)組。

注解

所有數(shù)據(jù)會被自動轉(zhuǎn)義,生成安全的查詢語句。

更新數(shù)據(jù)

$this->db->replace()

該方法用于執(zhí)行一條 REPLACE 語句,REPLACE 語句根據(jù)表的主鍵唯一索引 來執(zhí)行,類似于標(biāo)準(zhǔn)的 DELETE + INSERT 。 使用這個方法,你不用再手工去實(shí)現(xiàn) select(),update(),delete() 以及 insert() 這些方法的不同組合,為你節(jié)約大量時間。

例如:

$data = array(
    'title' => 'My title',
    'name'  => 'My Name',
    'date'  => 'My date'
);

$this->db->replace('table', $data);

// Executes: REPLACE INTO mytable (title, name, date) VALUES ('My title', 'My name', 'My date')

上面的例子中,我們假設(shè) title 字段是我們的主鍵,那么如果我們數(shù)據(jù)庫里有一行 的 title 列的值為 'My title',這一行將會被刪除并被我們的新數(shù)據(jù)所取代。

也可以使用 set() 方法,而且所有字段都被自動轉(zhuǎn)義,正如 insert() 方法一樣。

$this->db->set()

該方法用于設(shè)置新增或更新的數(shù)據(jù)。

該方法可以取代直接傳遞數(shù)據(jù)數(shù)組到 insert 或 update 方法:

$this->db->set('name', $name);
$this->db->insert('mytable');  // Produces: INSERT INTO mytable (name) VALUES ('{$name}')

如果你多次調(diào)用該方法,它會正確組裝出 INSERT 或 UPDATE 語句來:

$this->db->set('name', $name);
$this->db->set('title', $title);
$this->db->set('status', $status);
$this->db->insert('mytable');

set() 方法也接受可選的第三個參數(shù)($escape),如果設(shè)置為 FALSE,數(shù)據(jù)將不會自動轉(zhuǎn)義。 為了說明兩者之間的區(qū)別,這里有一個帶轉(zhuǎn)義的 set() 方法和不帶轉(zhuǎn)義的例子。

$this->db->set('field', 'field+1', FALSE);
$this->db->insert('mytable'); // gives INSERT INTO mytable (field) VALUES (field+1)
$this->db->set('field', 'field+1');
$this->db->insert('mytable'); // gives INSERT INTO mytable (field) VALUES ('field+1')

你也可以傳一個關(guān)聯(lián)數(shù)組作為參數(shù):

$array = array(
    'name' => $name,
    'title' => $title,
    'status' => $status
);

$this->db->set($array);
$this->db->insert('mytable');

或者一個對象:

/*
class Myclass {
    public $title = 'My Title';
    public $content = 'My Content';
    public $date = 'My Date';
}
*/

$object = new Myclass;
$this->db->set($object);
$this->db->insert('mytable');

$this->db->update()

該方法根據(jù)你提供的數(shù)據(jù)生成一條 UPDATE 語句并執(zhí)行,它的參數(shù)是一個數(shù)組 或一個對象,下面是使用數(shù)組的例子:

$data = array(
    'title' => $title,
    'name' => $name,
    'date' => $date
);

$this->db->where('id', $id);
$this->db->update('mytable', $data);
// Produces: // UPDATE mytable  // SET title = '{$title}', name = '{$name}', date = '{$date}' // WHERE id = $id

或者你可以使用一個對象:

/*
class Myclass {
    public $title = 'My Title';
    public $content = 'My Content';
    public $date = 'My Date';
}
*/

$object = new Myclass;
$this->db->where('id', $id);
$this->db->update('mytable', $object);
// Produces: // UPDATE mytable  // SET title = '{$title}', name = '{$name}', date = '{$date}' // WHERE id = $id

注解

所有數(shù)據(jù)會被自動轉(zhuǎn)義,生成安全的查詢語句。

你應(yīng)該注意到 $this->db->where() 方法的使用,它可以為你設(shè)置 WHERE 子句。 你也可以直接使用字符串形式設(shè)置 WHERE 子句:

$this->db->update('mytable', $data, "id = 4");

或者使用一個數(shù)組:

$this->db->update('mytable', $data, array('id' => $id));

當(dāng)執(zhí)行 UPDATE 操作時,你還可以使用上面介紹的 $this->db->set() 方法。

$this->db->update_batch()

該方法根據(jù)你提供的數(shù)據(jù)生成一條 UPDATE 語句并執(zhí)行,它的參數(shù)是一個數(shù)組 或一個對象,下面是使用數(shù)組的例子:

$data = array(
   array(
      'title' => 'My title' ,
      'name' => 'My Name 2' ,
      'date' => 'My date 2'
   ),
   array(
      'title' => 'Another title' ,
      'name' => 'Another Name 2' ,
      'date' => 'Another date 2'
   )
);

$this->db->update_batch('mytable', $data, 'title');

// Produces:
// UPDATE `mytable` SET `name` = CASE
// WHEN `title` = 'My title' THEN 'My Name 2'
// WHEN `title` = 'Another title' THEN 'Another Name 2'
// ELSE `name` END,
// `date` = CASE
// WHEN `title` = 'My title' THEN 'My date 2'
// WHEN `title` = 'Another title' THEN 'Another date 2'
// ELSE `date` END
// WHERE `title` IN ('My title','Another title')

第一個參數(shù)為要更新的表名,第二個參數(shù)為要更新的數(shù)據(jù),是個二維數(shù)組,第三個 參數(shù)是 WHERE 語句的鍵。

注解

所有數(shù)據(jù)會被自動轉(zhuǎn)義,生成安全的查詢語句。

注解

取決于該方法的內(nèi)部實(shí)現(xiàn),在這個方法之后調(diào)用 affected_rows() 方法 返回的結(jié)果可能會不正確。但是你可以直接使用該方法的返回值,代表了受影響的行數(shù)。

$this->db->get_compiled_update()

該方法和 $this->db->get_compiled_insert() 方法完全一樣,除了生成的 SQL 語句是 UPDATE 而不是 INSERT。

查看 $this->db->get_compiled_insert() 方法的文檔獲取更多信息。

注解

該方法不支持批量更新。

刪除數(shù)據(jù)

$this->db->delete()

該方法生成 DELETE 語句并執(zhí)行。

$this->db->delete('mytable', array('id' => $id));  // Produces: // DELETE FROM mytable  // WHERE id = $id

第一個參數(shù)為表名,第二個參數(shù)為 WHERE 條件。你也可以不用第二個參數(shù), 使用 where() 或者 or_where() 函數(shù)來替代它:

$this->db->where('id', $id);
$this->db->delete('mytable');

// Produces:
// DELETE FROM mytable
// WHERE id = $id

如果你想要從多個表中刪除數(shù)據(jù),你也可以將由多個表名構(gòu)成的數(shù)組傳給 delete() 方法。

$tables = array('table1', 'table2', 'table3');
$this->db->where('id', '5');
$this->db->delete($tables);

如果你想要刪除一個表中的所有數(shù)據(jù),可以使用 truncate() 或 empty_table() 方法。

$this->db->empty_table()

該方法生成 DELETE 語句并執(zhí)行:

$this->db->empty_table('mytable'); // Produces: DELETE FROM mytable

$this->db->truncate()

該方法生成 TRUNCATE 語句并執(zhí)行。

$this->db->from('mytable');
$this->db->truncate();

// or

$this->db->truncate('mytable');

// Produce:
// TRUNCATE mytable

注解

如果 TRUNCATE 語句不可用,truncate() 方法將執(zhí)行 "DELETE FROM table"。

$this->db->get_compiled_delete()

該方法和 $this->db->get_compiled_insert() 方法完全一樣,除了生成的 SQL 語句是 DELETE 而不是 INSERT。

查看 $this->db->get_compiled_insert() 方法的文檔獲取更多信息。

鏈?zhǔn)椒椒?/h2>

通過將多個方法連接在一起,鏈?zhǔn)椒椒梢源蟠蟮暮喕愕恼Z法。感受一下這個例子:

$query = $this->db->select('title')
        ->where('id', $id)
        ->limit(10, 20)
        ->get('mytable');

查詢構(gòu)造器緩存

盡管不是 "真正的" 緩存,查詢構(gòu)造器允許你將查詢的某個特定部分保存(或 "緩存")起來, 以便在你的腳本執(zhí)行之后重用。一般情況下,當(dāng)查詢構(gòu)造器的一次調(diào)用結(jié)束后,所有已存儲的信息 都會被重置,以便下一次調(diào)用。如果開啟緩存,你就可以使信息避免被重置,方便你進(jìn)行重用。

緩存調(diào)用是累加的。如果你調(diào)用了兩次有緩存的 select(),然后再調(diào)用兩次沒有緩存的 select(), 這會導(dǎo)致 select() 被調(diào)用4次。

有三個可用的緩存方法方法:

$this->db->start_cache()

如需開啟緩存必須先調(diào)用此方法,所有支持的查詢類型(見下文)都會被存儲起來供以后使用。

$this->db->stop_cache()

此方法用于停止緩存。

$this->db->flush_cache()

此方法用于清空緩存。

這里是一個使用緩存的例子:

$this->db->start_cache();
$this->db->select('field1');
$this->db->stop_cache();
$this->db->get('tablename');
//Generates: SELECT `field1` FROM (`tablename`)

$this->db->select('field2');
$this->db->get('tablename');
//Generates:  SELECT `field1`, `field2` FROM (`tablename`)

$this->db->flush_cache();
$this->db->select('field2');
$this->db->get('tablename');
//Generates:  SELECT `field2` FROM (`tablename`)

注解

支持緩存的語句有: select, from, join, where, like, group_by, having, order_by, set

重置查詢構(gòu)造器

$this->db->reset_query()

該方法無需執(zhí)行就能重置查詢構(gòu)造器中的查詢,$this->db->get() 和 $this->db->insert() 方法也可以用于重置查詢,但是必須要先執(zhí)行它。和這兩個方法一樣,使用查詢構(gòu)造器緩存_ 緩存下來的查詢不會被重置。

當(dāng)你在使用查詢構(gòu)造器生成 SQL 語句(如:$this->db->get_compiled_select()), 之后再執(zhí)行它。這種情況下,不重置查詢緩存將非常有用:

// Note that the second parameter of the get_compiled_select method is FALSE
$sql = $this->db->select(array('field1','field2'))
                ->where('field3',5)
                ->get_compiled_select('mytable', FALSE);

// ...
// Do something crazy with the SQL code... like add it to a cron script for
// later execution or something...
// ...

$data = $this->db->get()->result_array();

// Would execute and return an array of results of the following query:
// SELECT field1, field1 from mytable where field3 = 5;

注解

如果你正在使用查詢構(gòu)造器緩存功能,連續(xù)兩次調(diào)用 get_compiled_select() 方法 并且不重置你的查詢,這將會導(dǎo)致緩存被合并兩次。舉例來說,譬如你正在緩存 select() 方法,那么會查詢兩個相同的字段。

Class Reference

classCI_DB_query_builder

reset_query()

返回: CI_DB_query_builder instance (method chaining)
返回類型: CI_DB_query_builder

Resets the current Query Builder state. Useful when you want to build a query that can be cancelled under certain conditions.

start_cache()

返回: CI_DB_query_builder instance (method chaining)
返回類型: CI_DB_query_builder

Starts the Query Builder cache.

stop_cache()

返回: CI_DB_query_builder instance (method chaining)
返回類型: CI_DB_query_builder

Stops the Query Builder cache.

flush_cache()

返回: CI_DB_query_builder instance (method chaining)
返回類型: CI_DB_query_builder

Empties the Query Builder cache.

set_dbprefix([$prefix = ''])

參數(shù):

  • $prefix (string) -- The new prefix to use

返回: The DB prefix in use

返回類型: string

Sets the database prefix, without having to reconnect.

dbprefix([$table = ''])

參數(shù):

  • $table (string) -- The table name to prefix

返回: The prefixed table name

返回類型: string

Prepends a database prefix, if one exists in configuration.

count_all_results([$table = ''[, $reset = TRUE]])

參數(shù):

  • $table (string) -- Table name
  • $reset (bool) -- Whether to reset values for SELECTs

返回: Number of rows in the query result

返回類型: int

Generates a platform-specific query string that counts all records returned by an Query Builder query.

get([$table = ''[, $limit = NULL[, $offset = NULL]]])

參數(shù):

  • $table (string) -- The table to query
  • $limit (int) -- The LIMIT clause
  • $offset (int) -- The OFFSET clause

返回: CI_DB_result instance (method chaining)

返回類型: CI_DB_result

Compiles and runs SELECT statement based on the already called Query Builder methods.

get_where([$table = ''[, $where = NULL[, $limit = NULL[, $offset = NULL]]]])

參數(shù):

  • $table (mixed) -- The table(s) to fetch data from; string or array
  • $where (string) -- The WHERE clause
  • $limit (int) -- The LIMIT clause
  • $offset (int) -- The OFFSET clause

返回: CI_DB_result instance (method chaining)

返回類型: CI_DB_result

Same as get(), but also allows the WHERE to be added directly.

select([$select = '*'[, $escape = NULL]])

參數(shù):

  • $select (string) -- The SELECT portion of a query
  • $escape (bool) -- Whether to escape values and identifiers

返回: CI_DB_query_builder instance (method chaining)

返回類型: CI_DB_query_builder

Adds a SELECT clause to a query.

select_avg([$select = ''[, $alias = '']])

參數(shù):

  • $select (string) -- Field to compute the average of
  • $alias (string) -- Alias for the resulting value name

返回: CI_DB_query_builder instance (method chaining)

返回類型: CI_DB_query_builder

Adds a SELECT AVG(field) clause to a query.

select_max([$select = ''[, $alias = '']])

參數(shù):

  • $select (string) -- Field to compute the maximum of
  • $alias (string) -- Alias for the resulting value name

返回: CI_DB_query_builder instance (method chaining)

返回類型: CI_DB_query_builder

Adds a SELECT MAX(field) clause to a query.

select_min([$select = ''[, $alias = '']])

參數(shù):

  • $select (string) -- Field to compute the minimum of
  • $alias (string) -- Alias for the resulting value name

返回: CI_DB_query_builder instance (method chaining)

返回類型: CI_DB_query_builder

Adds a SELECT MIN(field) clause to a query.

select_sum([$select = ''[, $alias = '']])

參數(shù):

  • $select (string) -- Field to compute the sum of
  • $alias (string) -- Alias for the resulting value name

返回: CI_DB_query_builder instance (method chaining)

返回類型: CI_DB_query_builder

Adds a SELECT SUM(field) clause to a query.

distinct([$val = TRUE])

參數(shù):

  • $val (bool) -- Desired value of the "distinct" flag

返回: CI_DB_query_builder instance (method chaining)

返回類型: CI_DB_query_builder

Sets a flag which tells the query builder to add a DISTINCT clause to the SELECT portion of the query.

from($from)

參數(shù):

  • $from (mixed) -- Table name(s); string or array

返回: CI_DB_query_builder instance (method chaining)

返回類型: CI_DB_query_builder

Specifies the FROM clause of a query.

join($table, $cond[, $type = ''[, $escape = NULL]])

參數(shù):

    以上內(nèi)容是否對您有幫助:
    在線筆記
    App下載
    App下載

    掃描二維碼

    下載編程獅App

    公眾號
    微信公眾號

    編程獅公眾號