Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Random record from mysql database with CodeIgniter

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 />'; } 
like image 202
designer-trying-coding Avatar asked Oct 26 '09 23:10

designer-trying-coding


2 Answers

Codeigniter provides the ability to order your results by 'RANDOM' when you run a query. For instance

function get_random_page() {     $this->db->order_by('id', 'RANDOM');     or     $this->db->order_by('rand()');     $this->db->limit(1);     $query = $this->db->get('pages');     return $query->result_array();  } 

I've used this before and found it to work fine. Hope that helps

like image 106
Patrick O'Doherty Avatar answered Sep 29 '22 12:09

Patrick O'Doherty


I don't know about codeigniter, but getting a random dataset is

SELECT * FROM table ORDER BY RAND() LIMIT 1 

The relevant part is "ORDER BY RAND()", obviously.

like image 31
ty812 Avatar answered Sep 29 '22 11:09

ty812