读取数据库随机的信息

<?php

require 'system/include/common.inc.php ';

$n = 10; //随机显示的记录数
$results = $result = array(); //记录结果的数组

$rowNum = mysql_result(mysql_query( "SELECT COUNT(*) AS cnt FROM test "), 0, 0);

echo $rowNum;

if($rowNum < 50) { //数据量小的话,这样反而可以提高效率,当然50可以随便改

$query = mysql_query( "SELECT * FROM test ORDER BY rand() LIMIT 0,$n ");
while($result = mysql_fetch_array($query)) {
$results[$result[ 'id ']] = $result;
}

} else {

//随机的范围
$maxNum = mysql_result(mysql_query( "SELECT MAX(id) AS maxid FROM test "), 0, 0);
$minNum = 1;

//存放记录的数组
$results = array();

//存放生成的id,用来判断是否已经出现过!
$existIds = array();

//随机的id集合 格式为 xx,xx,xx,xx,用来查询记录
$limitNum = $randId = $randIds = ' ';

//根据已经产生的记录来动态控制下次查询的记录数
$limitNum = $n;

do {

$query = $result = ' ';

$randIds = ' '; //清除上次查询id

$comma = ' ';

$j = 0;
while($j < $n) { //while($j < 2 * $n) { 随机产生n个数字,可以增加一定值,来加大命中率

mt_srand((float)microtime() * 1000000);
$randId = mt_rand($minNum, $maxNum);

if(!in_array($randId, $existIds)) {
$existIds[] = $randId; //将产生的id全部记录到$existIds数组中,用来产生不重复的记录id
$randIds .= $comma . $randId;
$comma = ', ';
$j++;
}
}

$query = $db-> query( "SELECT * FROM test WHERE id IN ($randIds) LIMIT 0,$limitNum ");
while($result = mysql_fetch_array($query)) { //找到记录记录内容,重新随机
$results[$result[ 'id ']] = $result; //记录结果内容

}

$limitNum = $n - count($results);

}while(count($results) < $n);

}

var_dump($results);

?>

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值