使用CodeIgniter从mysql数据库中随机记录 [英] Random record from mysql database with CodeIgniter

查看:342
本文介绍了使用CodeIgniter从mysql数据库中随机记录的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我通过互联网进行了研究,但找不到任何东西...

I researched over the internet, but could not find anything...

我有一个mysql数据库,并在一个表中记录,并且我需要在每次页面加载时从该表中获取随机记录.我怎样才能做到这一点?有功能吗?

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?

赞赏!谢谢

已排序: 链接: 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 />';
}

推荐答案

Codeigniter提供了在运行查询时按"RANDOM"对结果进行排序的功能.例如

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

这篇关于使用CodeIgniter从mysql数据库中随机记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆