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)
//纯手写的,不明白可以问我,记得给分
/*** 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
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)