简体   繁体   中英

Best practice in writing queries in codeigniter

I would like to know whats the best practice in writing a database (mysql) query in codeigniter. i have seen many different ways but was confused what would be the best practice.

Following are few methods i have gone through

Method 1

$this -> db -> select('id, username, password');
$this -> db -> from('users');
$this -> db -> where('username = ' . "'" . $username . "'");
$this -> db -> where('password = ' . "'" . MD5($password) . "'");
$this -> db -> limit(1);

Method 2

$query = $this->db->query("select * from user where username = '$uname' and password = '$pass'");

Method 3 (writing a stored procedure)

$query = "call authenticateuser(" . $this->db->escape($parameters['username']) . ", '" . sha1($parameters['password']) . "')";

There might may be many other ways, but would like to know what the best way in writing a query, therefore if anyone could advise, it would be really helpful.

Active records so best is method1 with little refactoring:

$this->db->select('id, username, password');
$this->db->from('users');
$this->db->where('username',$username);
$this->db->where('password', MD5($password));
$this->db->limit(1);

check your where() and mine where() :)

Active record query building is more comfortable, and readable when building queries, expecially if you need many filters where,like,order_by,join,limit writing down by hands the queries should be probably little faster, but i encourage you to use active record building.

i usually this to get data from database, it very easy and quick;

My model:

public function getdata($select,$table,$where,$limit,$offset,$order){

        if(isset($select) && !empty($select)){
            $this->db->select("$select");
        }
        if(isset($limit) && !empty($limit)){
            if(isset($offset) && !empty($offset)){
                $this->db->limit($limit,$offset);
            }
            else{
                $this->db->limit($limit);
            }
        }
        if(isset($where) && !empty($where)){
            foreach ($where as $key => $value) {
                $this->db->where($key,$value);
            }
        }
        if(isset($order) && !empty($order)){
            foreach ($order as $key => $value) {
                $this->db->order_by($key,$value);
            }
        }

        $query = $this->db->get("$table");
        return $query->result();
    }

My Controller:

$this->my_model->getdata('','user',array('userid' =>  1,'username' => 'my_username'),'','','');

this means:

select * from user where userid = 1 and username = 'my_username';

other example:

$this->my_model->getdata('username','user','',10,'','','');

means:

select username from user limit 10;

//my_model is model class name;

For me I'm using Stored Procedure although it is tedious in coding but the advantage are easy in maintenance, security and speed. Here is my example:

   function user_list($str_where, $str_order, $str_limit){

     $str_where  = $this->db->call_function('real_escape_string', $this->db->conn_id, $str_where);
    $str_order  = $this->db->call_function('real_escape_string', $this->db->conn_id, $str_order);
    $str_limit  = $this->db->call_function('real_escape_string', $this->db->conn_id, $str_limit);

$qry_res    = $this->db->query("CALL rt_sample_list('{$str_where}', '{$str_order}', '{$str_limit}');");
    $res        = $qry_res->result();

    $qry_res->next_result(); // Dump the extra resultset.
    $qry_res->free_result(); // Does what it says.

    return $res;

}

I use my own crud_model which is based upon CI's Active record in actual. It's better to pass $params array rather flooding functions with parameters.

In my Model:

//for JOINS etc stuff

public function get_joined_data($params){

    if (!empty($params['select'])) {
        $this->db->select($params['select']);
    }
    $this->db->from($params['from']);

    if (is_array($params['join']) || count($params['join']) > 1) {
        foreach ($params['join'] as $key => $value) {
            $join_values = explode(',', $value);
            $this->db->join($join_values[0], $join_values[1], $join_values[2]);
        }
    } else{
        $join_values = explode(',', $params['join'][0]);
        $this->db->join($join_values[0], $join_values[1], $join_values[2]);
    }

    if (!empty($params['key']) && !empty($params['where'])) {
        $this->db->where($params['key'], $params['where']);
    } else if (is_array($params['where'])) {

        $this->db->where($params['where']);
    }
    if (isset($params['like']) && is_array($params['like'])) {
        $this->db->like($params['like']);
    }
    if (isset($params['orderby']) && is_array($params['orderby'])) {
        foreach ($params['orderby'] as $name => $order) {
            $this->db->order_by($name, $order);
        }
    }
    if (isset($params['limit'])) {
        $this->db->limit($params['limit']['count'], $params['limit']['start']);
    }
    $query = $this->db->get();
    return $query->result();
}

And in Controller:

//joins()

$params = array(
    'from' => '$from',
    'join' => $join_arr,  
    'where' => $where_arr, 
    'orderby' => $orderby_arr 
    );`enter code here`
$donors_data = $this->crud_model->get_joined_data($params);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM