Random record from mysql database with CodeIgniter

2019-04-03 09:06发布

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

11条回答
等我变得足够好
2楼-- · 2019-04-03 09:56
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.

查看更多
女痞
3楼-- · 2019-04-03 09:59

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.

查看更多
啃猪蹄的小仙女
4楼-- · 2019-04-03 10:04

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

查看更多
孤傲高冷的网名
5楼-- · 2019-04-03 10:04

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();
查看更多
兄弟一词,经得起流年.
6楼-- · 2019-04-03 10:04

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

查看更多
登录 后发表回答