查询
$this->db->query();
要提交一个查询,用以下函数:
$this->db->query('YOUR QUERY HERE');
query() 函数以object(对象)的形式返回一个数据库结果集. 当使用 "read" 模式来运行查询时, 你可以使用“显示你的结果集”来显示查询结果; 当使用 "write" 模式来运行查询时, 将会仅根据执行的成功或失败来返回 TRUE 或 FALSE. 当你需要将返回的结果赋值给一个自定义变量的时候, 你可以这样操作:
$query = $this->db->query('YOUR QUERY HERE');
$this->db->simple_query();
This is a simplified version of the $this->db->query() function. It ONLY returns TRUE/FALSE on success or failure. It DOES NOT return a database result set, nor does it set the query timer, or compile bind data, or store your query for debugging. It simply lets you submit a query. Most users will rarely use this function.
这是一个简化版本的 $this->db->query() 函数. 它仅返回 True(bool) 和 False(bool) 以表示查询成功与失败. 它将不会返回查询数据集,无法设置查询计时器(设置环境变量),无法编译绑定数据,不能够存储查询诊断信息。 简单地说,他是一个用于提交查询的函数,对于大多数用户而言并不会使用到它。
手工添加数据库前缀 (Adding Database prefixes manually)
If you have configured a database prefix and would like to add it in manually for, you can use the following.
如果你需要为一个数据库手工添加前缀,你可以使用以下步骤。
$this->db->dbprefix('tablename');
// outputs prefix_tablename
保护标识符 (Protecting identifiers)
In many databases it is advisable to protect table and field names - for example with backticks in MySQL. Active Record queries are automatically protected, however if you need to manually protect an identifier you can use:
在许多数据库中,保护表(table)和字段(field)的名称是可取的,例如在MySQL、Active Record的查询都是自动保护的。不管怎样,如果您需要手动保护一个标识符,您也可以使用以下:
$this->db->protect_identifiers('table_name');
转义查询 (Escaping Queries)
It's a very good security practice to escape your data before submitting it into your database. CodeIgniter has two functions that help you do this:
将数据转义以后提交到你的数据库是非常好的安全做法,CodeIgniter提供了两个函数帮助你完成这个工作。
- $this->db->escape() 这个函数将会确定数据类型,以便仅对字符串类型数据进行转义。它将会自动增加单引号(single quotes)在数据的周围,所以你不能这样做:
$sql = "INSERT INTO table (title) VALUES(".$this->db->escape($title).")"; - $this->db->escape_str() 此函数将忽略数据类型对传入数据进行转义。更多时候你将使用上面的函数而不是这个。这个函数的使用方法是:
$sql = "INSERT INTO table (title) VALUES('".$this->db->escape_str($title)."')";
Query Bindings
Bindings enable you to simplify your query syntax by letting the system put the queries together for you. Consider the following example:
$sql = "SELECT * FROM some_table WHERE id = ? AND status = ? AND author = ?";
$this->db->query($sql, array(3, 'live', 'Rick'));
The question marks in the query are automatically replaced with the values in the array in the second parameter of the query function.
The secondary benefit of using binds is that the values are automatically escaped, producing safer queries. You don't have to remember to manually escape data; the engine does it automatically for you.