Welcome Guest, Not a member yet? Register   Sign In
Best Practice
#2

(This post was last modified: 10-09-2018, 11:48 PM by Pertti.)

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) {
    
$a 1;
}

if (
$c == 3) {
    
$d 1;
}

// building query manually
$sql 'SELECT * FROM table1';
if (isset(
$a) || isset($d)) {
    
$sql .= ' WHERE';
    if (isset(
$a)) {
        
$sql .= ' a = '.$a;
        if (isset(
$b)) {
             
$sql .= ' AND';
        }
    }
    if (isset(
$b)) {
        
$sql .= ' b = '.$b;
    }
}
$q $this->db->query($sql);

// same query using query builder
if (isset($a)) {
    
$this->db->where('a'$a);
}
if (isset(
$b)) {
    
$this->db->where('b'$b);
}
$q $this->db->get('table1'); 
;

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);
if (
$b == 2) {
    
// only call query if this condition matches
    
$q1 $this->db->get('table1');
}

$q2 $this->db->get('table2');
// If $b == 2 -> SELECT * FROM table2
// If $b != 2 -> SELECT * FROM table2 WHERE a = 1 

I personally like using query builder over trying to build the query string manually myself.
Reply


Messages In This Thread
Best Practice - by emilio - 10-09-2018, 07:19 PM
RE: Best Practice - by Pertti - 10-09-2018, 11:42 PM
RE: Best Practice - by php_rocs - 10-10-2018, 07:29 AM
RE: Best Practice - by dave friend - 10-10-2018, 08:04 AM
RE: Best Practice - by emilio - 10-12-2018, 10:24 AM



Theme © iAndrew 2016 - Forum software by © MyBB