Random record from mysql database with CodeIgniter

79,341

Solution 1

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

Solution 2

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.

Solution 3

Do you know how many records there are in the table? You could do something like this:

$count=mysql_exec('select count(*)-1 from some_table');
$count=rand(1,$count);

then:

select * from
some_Table
limit $count,1

Solution 4

This code snippet worked well for me.

$this->db->select('name');
$this->db->order_by('rand()');
$this->db->limit(1);
$query = $this->db->get('<table>'); //<table> is the db table name
return $query->result_array();

Solution 5

Getting random record from large table is very expensive. Don't use ORDER BY RAND().

This is a bad idea, but if you have a small table no problem. In a huge databases this type of queries very slow.

Share:
79,341
designer-trying-coding
Author by

designer-trying-coding

Updated on January 02, 2021

Comments

  • designer-trying-coding
    designer-trying-coding over 3 years

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