![]() |
Best Practice - Printable Version +- CodeIgniter Forums (https://forum.codeigniter.com) +-- Forum: Using CodeIgniter (https://forum.codeigniter.com/forumdisplay.php?fid=5) +--- Forum: Libraries & Helpers (https://forum.codeigniter.com/forumdisplay.php?fid=11) +--- Thread: Best Practice (/showthread.php?tid=71913) |
Best Practice - emilio - 10-09-2018 Hello, I have a doubt about using query on CI. Should I prefer Standard Query or is better I use Query Builder? In other words, pro and cons about Standard Query and Query Builder. Tanks in advance RE: Best Practice - Pertti - 10-09-2018 So you are talking about either manually writing SQL queries (SELECT x FROM t WHERE a = 'b') v using query builder $q = $this->db->select('x')->where('a', 'b')->get('t'); ? The main difference is, for first option you are building the string for the query yourself, for other, you are using, in my humble opinion, nicer way to add logic. PHP Code: if ($b == 2) { Additionally, query builder automatically escapes all values so you don't have to worry about SQL injection. On down side, because it's building everything in $this->db instance, you have to make sure when you start building your query, that you also launch it, or flush everything before you start putting together another query: PHP Code: $this->db->where('a', 1); I personally like using query builder over trying to build the query string manually myself. RE: Best Practice - php_rocs - 10-10-2018 @emilio, I prefer using a combo (writing my own queries and using the CI query binding feature) ... (https://codeigniter.com/user_guide/database/queries.html?highlight=query%20bind#query-bindings ). RE: Best Practice - dave friend - 10-10-2018 My opinion? Query Builder (QB) is a great tool, but like any tool, it isn't appropriate for every task. Most often I rely on good old $this->db->query(). And when the query requires inputs use Query Bindings so the values are escaped. The most important thing to know about QB is that it takes all the QB methods you called to create a string and then, quite literally, calls query() using the constructed string. Very often it makes little sense to jump through all the QB hoops just to build a simple query string, e.g. PHP Code: $query = $this->db->query("SELECT * from events"); The real value of QB - where it really shines - is when you want to produce different query strings based on some condition. Here's a very partial list of potential changes/conditions.
PHP Code: /** The above method might be called multiple times depending on the number of fields the user selected to search. QB makes this kind of problem pretty easy to solve. RE: Best Practice - emilio - 10-12-2018 Thank You for your expleining, I appreciated all three comments. Forgive my delay but I had an accident and I was stopped some days in the bed withouth the option to use a PC or a tablet. Anyway, Thanx, your comments helped me very much. |