Codeigniter simple_query vs. query builder (insert

2020-04-16 06:23发布

问题:

As per documentation, simple_query will not return any database result set, nor does it set the query timer, or compile bind data, or store your query for debugging.

As in my CodeIgniter I am using query builder provided by CI to generate queries.

So if these query builders for insert, update and delete works in the same way like simple_query or they work differently in the background?

回答1:

simple_query() is the only database method in CodeIgniter that behaves as you have pointed out. As the documentation states: "Most users will rarely use this function."

With a few exceptions, all other Query Builder methods return either a DB_query_builder instance a CI_DB_result object or - in the case of "write" type queries - a Boolean that indicates success or failure. The few exceptions return an integer, string or mixed (a value or FALSE).

All methods that accept input values escape (or optionally not escape) the values provided.

While Query Builder (QB) is a great tool it is often not necessary. Using $this->db->query('your statement here'); is frequently more efficient. Understand the goal of QB is to create a string that is literally used in a call to db->query('a query string');.

So instead of typing all this...

$this->db->select('id, name, email');
$this->db->from('customers');
$this->db->where('id', $id)
$this->db->where('active', $is_active)
$query = $this->get();
$result = $query->result();

Typing the following produces the exact same results as the above because it directly provides the query string that QB built in the above code. (The query is fully escaped too.) But it executes a ton less code to get there. (With Less typing.)

$query = $this->db->query("Select id, name, email from customers where id = ? and active = ?", [$id, $is_active]);
$result = $query->result();

This is an example of using Query Binding

Studying the core source code (mostly in 'driver' files) will show you where using simple_query() is appropriate and useful.