Ways to Retrieve Data from MySQL Database Using CodeIgniter

I use CI 1.7.2

This code should resides in model class. In short, this is the model you need to consider,

<?php
class Data_model extends Model {
/* we are going to use this getSome for example purpose */
	function getSome() {

/*all the code displayed below need to be inserted here */

/* standard row thing... its better to put this loop inside macros */
		if($q->num_rows() > 0) {
			foreach ($q->result() as $row) {
			    $data[] = $row;
			}
		return $data;
		}
	}
}

assuming q is the query and there is data table available somewher with id, title, author and contents column

First way, write yourself

$q = $this->db->query("SELECT * FROM data");

Second way, same sql query but with prepared statement to prevent sql injection.

 $sql = "SELECT title,author,contents FROM data WHERE id = ? AND author =?";
 $q = $this->db->query($sql, array(4,"Author two") );

Third way, use active record way-ish

$q = $this->db->get('data');

Fourth way, same like third way but with additional parameters specifying which column to retrieve. Should be faster than the second one.

$this->db->select('title, contents');
$q = $this->db->get('data');

Fifth way, same like fourth way but with more parameters specified separately for easier reading.

$this->db->select('title, contents');
$this->db->from('data');
$this->db->where('id', 1);
$q = $this->db->get();

Related posts:

  1. Storing Java.Util.Date into Mysql DateTime Column
  1. noob2288 says:

    thank you for the list. help me so much

  2. Alex says:

    great help thanks.

  1. There are no trackbacks for this post yet.

Leave a Reply