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 />';
}
1
  • $this->db->order_by('rand()'); is the line which you add into your code to get random results Commented Jun 9, 2016 at 9:53

12 Answers 12

102

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.

Sign up to request clarification or add additional context in comments.

2 Comments

for large table, this solution is very slow! best method is generate a random number in php and SELECT and WHERE in mysql. @RajSar 's method is simular to this.
@user57750 that's unreliable. What if some of the records were corrupt or had been removed?
6

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.

1 Comment

hey thanks, from your clue, I found the link derekallard.com/blog/post/… :) sorted!
4

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

1 Comment

I think this is the best way, but should it be Limit $count, 1 ?
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();

Comments

3

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.

Comments

2

I use codeigniter with datamapper. This is the code which I use to get a record randomly from table Advertiser:

 $ad = new Advertiser();
 $ad->limit(3);
 $ad->order_by('id', 'RANDOM');
 $ad->get();

Comments

2
SELECT product_id, title, description
FROM products
WHERE active = 1
AND stock > 0
ORDER BY RAND()
LIMIT 4

The ORDER BY RAND() clause returns random records! You can limit records also using LIMIT.

Comments

1

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

Comments

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 ...

Comments

0

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()

Comments

0

This function retrieve all rows in table in random order

public function get_questions(){
    $this->db->select('*');
    $this->db->order_by('rand()');
    $this->db->from('multiple_choices');
    $query = $this->db->get();
    return $query->result_array();
}

Comments

0

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)];

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.