查詢
$this->db->query();
要提交一個查詢,用以下函數(shù):
$this->db->query('YOUR QUERY HERE');
query() 函數(shù)以object(對象)的形式返回一個數(shù)據(jù)庫結(jié)果集. 當使用 "read" 模式來運行查詢時, 你可以使用“顯示你的結(jié)果集”來顯示查詢結(jié)果; 當使用 "write" 模式來運行查詢時, 將會僅根據(jù)執(zhí)行的成功或失敗來返回 TRUE 或 FALSE. 當你需要將返回的結(jié)果賦值給一個自定義變量的時候, 你可以這樣操作:
$query = $this->db->query('YOUR QUERY HERE');
$this->db->simple_query();
這是一個簡化版本的 $this->db->query() 函數(shù). 它僅返回 True(bool) 和 False(bool) 以表示查詢成功與失敗. 它將不會返回查詢數(shù)據(jù)集,無法設(shè)置查詢計時器(設(shè)置環(huán)境變量),無法編譯綁定數(shù)據(jù),不能夠存儲查詢診斷信息。 簡單地說,他是一個用于提交查詢的函數(shù),對于大多數(shù)用戶而言并不會使用到它。
Working with Database prefixes manually
If you have configured a database prefix and would like to prepend it to a table name for use in a native SQL query for example, then you can use the following:
$this->db->dbprefix('tablename');
// outputs prefix_tablename
If for any reason you would like to change the prefix programatically without needing to create a new connection, you can use this method:
$this->db->set_dbprefix('newprefix');
$this->db->dbprefix('tablename');
// outputs newprefix_tablename
保護標識符
在許多數(shù)據(jù)庫中,保護表(table)和字段(field)的名稱是明智的,例如在MySQL中使用反引號。Active Record的查詢都已被自動保護,然而,如果您需要手動保護一個標識符,您也可以這樣:
$this->db->protect_identifiers('table_name');
這個函數(shù)也會給你的表名添加一個前綴,它假定在你的數(shù)據(jù)庫配置文件中已指定了一個前綴??赏ㄟ^將第二個參數(shù)設(shè)置為TRUE (boolen) 啟用前綴:
$this->db->protect_identifiers('table_name', TRUE);
轉(zhuǎn)義查詢
將數(shù)據(jù)轉(zhuǎn)義以后提交到你的數(shù)據(jù)庫是非常好的安全做法,CodeIgniter 提供了 3 個函數(shù)幫助你完成這個工作。
-
$this->db->escape() 這個函數(shù)將會確定數(shù)據(jù)類型,以便僅對字符串類型數(shù)據(jù)進行轉(zhuǎn)義。并且,它也會自動把數(shù)據(jù)用單引號括起來,所以你不必手動添加單引號,用法如下:
$sql = "INSERT INTO table (title) VALUES(".$this->db->escape($title).")";
-
$this->db->escape_str() 此函數(shù)將忽略數(shù)據(jù)類型對傳入數(shù)據(jù)進行轉(zhuǎn)義。更多時候你將使用上面的函數(shù)而不是這個。這個函數(shù)的使用方法是:
$sql = "INSERT INTO table (title) VALUES('".$this->db->escape_str($title)."')";
-
$this->db->escape_like_str() This method should be used when strings are to be used in LIKE conditions so that LIKE wildcards ('%', '_') in the string are also properly escaped.
$search = '20% raise';
$sql = "SELECT id FROM table WHERE column LIKE '%".$this->db->escape_like_str($search)."%'";
封裝查詢
封裝,通過讓系統(tǒng)為你組裝各個查詢語句,能夠簡化你的查詢語法。參加下面的范例:
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));
查詢語句中的問號會自動被查詢函數(shù)中位于第二個參數(shù)位置的數(shù)組中的值所替代。
使用封裝查詢的第二個好處是所有的值都會被自動轉(zhuǎn)義,形成了較為安全的查詢語句。你無需手動地去轉(zhuǎn)義這些數(shù)據(jù);控制器將會自動為你進行。
?