Random record from mysql database with CodeIgniter

Viewed 82224

I researched over the internet, but could not find anything...

I have a mysql db, and records at a table, and I need to get random record from this table at every page load. how can I do that? Is there any func for that?

Appreciate! thanks


SORTED: link: http://www.derekallard.com/blog/post/ordering-database-results-by-random-in-codeigniter/

$this->db->select('name');
$query = $this->db->get('table');
$shuffled_query = $query->result_array();
shuffle ($shuffled_query);

foreach ($shuffled_query as $row) {
    echo $row['name'] . '<br />';
}
12 Answers

Lets think we have table where we deleted some rows. There is maybe ID not continues correctly. For sample id: 1,5,24,28,29,30,31,32,33 (9 rows)

mysql_num_rows returns 9

Another methods will return not existing rows: $count=9; //because mysql_num_rows()==9 $count=rand(1,$count); // returns 4 for sample, but we havn't row with id=4

But with my method you always get existing rows. You can separate code and use first 2 code anywhere on site.

// Inside of Controller Class
    function _getReal($id,$name_of_table)
 {
 $Q=$this->db->where('id',$id)->get($name_of_table);
 if($Q->num_rows()>0){return $Q;}else{return FALSE;}
 }

 function _getLastRecord($name_of_table)
 {
 $Q=$this->db->select("id")->order_by('id DESC')->limit("1")->get($name_of_table)->row_array();
 return $Q['id'];
 }

 function getrandom()
 {
       $name_of_table="news";
 $id=rand(1,$this->_getLastRecord($name_of_table));
 if($this->_getReal($id,$name_of_table)!==FALSE)
 {
         echo $id;
         // Here goes your code
 }
 else
 {
         $this->getrandom();
 }
// END

I think this is not best way. For sample, you've deleted record which is now==$count. You must iterate this for mysql_num_rows()

Random row without ORDER BY RAND() query:

$all_rows = $this->db->get('table')->result_array();
$random_row = $all_rows[rand(0,count($all_rows)-1)];
Related