Search code examples
mysqlcodeigniteractiverecordcodeigniter-2codeigniter-3

How to get random row from MYSQL and how to write it in active records?


This is my query

"SELECT * FROM package_info ORDER BY RAND() LIMIT 0,3;"

I try to write it in active records like this.

$this->db->select('*');
$this->db->from('package_info');
$this->db->order_by("id", "random");
$this->db->limit(0, 3);
$result = $this->db->get();

But it is not work. How to write this in active record?


Solution

  • Use Below code it will work fine -

    $this->db->select('*');
    $this->db->from('package_info');
    $this->db->order_by("id", "random");
    $this->db->limit(3, 0);
    $result = $this->db->get()->result(); 
    
    // shows last executed query
    echo $this->db->last_query();
    
    // shows data fetched
    echo "<pre>";
    print_r( $result );
    echo "</pre>";
    

    You can visit on this link to view how queries are used in Codeigniter. https://www.codeigniter.com/userguide2/database/active_record.html