* MySQL 随机取记录
*
* @param $t 表
* @param $c ID列,默认为id
* @param $n 取多少个
* @param $w 条件语句
* @param $f bool 是否强制以多维数组形式返回,默认false
* @return array 取1个直接返回结果数组(除非$f为true),取>1个返回多维数组,用foreach取出
*/
function rand_row($t , $c = 'id' , $n = '1', $w = '' , $f = false) {
$m=new mysqli(mysqli信息,自行查找php文档)
if (!empty($w)) {
$w = ' AND '.$w
}
$sql = "SELECT * FROM `{$t}` WHERE {$c} >= (SELECT floor(RAND() * (SELECT MAX({$c}) FROM `{$t}`))) {$w} ORDER BY {$c} LIMIT {$n}"
$xq = $m->query($sql)
$r = array()
while ($x = $m->fetch_array($xq)) {
$r[] = $x
}
if ($f == false && count($r) == 1) {
return $r[0]
} else {
return $r
}
}
//连接数据库if(!$con = mysql_connect("localhost","root","root")){die(mysql_error())}
mysql_select_db("ali_xt")
mysql_query('set names utf8')
//找出ali_admin表的字段
$res = mysql_query('show columns from ali_admin')
//将数据给弄出来
$data = array()
while ($row = mysql_fetch_assoc($res, MYSQL_NUM)) {
$data[] = $row
}
//随机个数,默认5
$rand_times = 5
$rand_times = count($data)<$rand_times?count($data):$rand_times
$result = array()
for( $i=0$i<$rand_times$i++ ){
$result[] = $data[rand(0,count($data)-1)][0]
}
echo "<pre>"
print_r($result) //输出5个随机字段
mysql_close($con)
//纯手写的,不明白可以问我,记得给分
1)随机取出5条记录用sql语句就行了mysql如下:"select
*
from
youtable
order
by
rand()
limit
5"
2)同样随机取5-10条:
$num=rand(5,10)
$sql="select
*
from
youtable
order
by
rand()
limit
$num"
ps:为什么不是php分类问题?
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)