Alex Rivera | Logout

Random record from mysql database with CodeIgniter

Asked 2009-10-26T23:39:44.477
33

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 />';
}
Edit
Report

1 Answer

1

Getting random record from large table is very expensive. But bellow this code is very effective ..

$count=mysql_num_rows(mysql_query("select * from table_name WHERE SOME_OF_YOUR_CONDITION"));
$nums=rand(1,$count);


mysql_query(" select * from table_name WHERE SOME_OF_YOUR_CONDITION LIMIT $count,1");

This will be helpful ...

answered 2013-04-05T17:15:35.973

Your Answer