What are the benefits of using Query Builders
Pardon my ignorance on the matter but what's the point of using Query Builders? Isn't it far more succinct to write one line of SQL instead of 3 lines of AR code:
$this->db->query(" SELECT title, contents FROM data WHERE id = 2 ");
Instead of:
$this->db->select('title, contents');
$this->db->from('data');
$this->db->where('id', 2);
It just seems more verbose to me but then again I know nothing about Query Builders so I could be missing something. Would really like to kno开发者_StackOverfloww what the benefits are.
If you need to programatically build your query CodeIgniter's Active Records are far more comfortable than plain text,
$id = 2;
//with CodeIgniter's Active Record
$this->db->select('title, contents');
$this->db->from('data');
if(isset($id))
$this->db->where('id', $id);
//without CodeIgniter's Active Record
if(isset($id))
$where = " WHERE id = {$id}";
$this->db->query(" SELECT title, contents FROM data".$where);
Ok, this isn't changing that much but what if you have 10 constraints on the where clause?
furthermore CodeIgniter's Active Record build the string in the right way (with placeholders ?
) according to the data you pass i.e. you won't have to insert the '
manually on the query.
EDIT
@Col. Shrapnel said that there are no benefits with CodeIgniter's Active Record, since I'm not in agree with him I try to enforce my thesis with another example:
Let's do an example for an INSERT statement:
$array = array('A'=>'aaaa','B'=>'bbbb','C'=>'cccc');
//without CodeIgniter's Active Record
$query = "INSERT INTO my_table (";
$query.= implode(',',array_keys($array)) .')';
$query.= ......
//with CodeIgniter's Active Record
$this->db->insert('my_table',$array);
I see no benefits at all.
So did Dalen say, "this isn't chanching that much".
And with 10 constraint on the where clause AR just become even more werbose and messy, making you completely unable to grasp the meaning of the query. And there are no joins yet!
The only thing you really needed is support for placeholders.
With placeholders your queries become safe and easy to compose.
The style of programming you are complaining about should be impervious to SQL injection attacks. That's assuming that the DB interface you're talking to does sensible quoting and escaping, of course.
精彩评论