Please wait for 15 seconds...

Friday 7 September 2012

One day, during a project I needed to fetch random data from database. I was using codeigniter so I had two ways either find a database method for it or hardcode whole sql query. I chose lazy method. I opened codeigniter user guide and digged into it. but there was no helpful instruction for my situation. So I decide to do some experiment. Here I am using a trick that worked for me, I hope it will also help you.


Although you can call database functions in controller but I highly recommend you use this code in your model class. The reason why I am saying not to call database functions in controller is because codeigniter is a MVC framework and calling database functions in controller does not follow MVC pattern.

class my_models extends CI_Model {
    public function __construct(){

    public function get_random(){

        $query = $this->db->get('my_table');
        return $query->result_array();

You can find more codeigniter database function in Active Record Class.

Good luck...

Posted by Atul


Post a Comment

Techsirius on Facebook