//連接數(shù)據(jù)庫
創(chuàng)新互聯(lián)建站-專業(yè)網(wǎng)站定制、快速模板網(wǎng)站建設(shè)、高性價比二道江網(wǎng)站開發(fā)、企業(yè)建站全套包干低至880元,成熟完善的模板庫,直接使用。一站式二道江網(wǎng)站制作公司更省心,省錢,快速模板網(wǎng)站建設(shè)找我們,業(yè)務(wù)覆蓋二道江地區(qū)。費用合理售后完善,10余年實體公司更值得信賴。
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');
//將數(shù)據(jù)給弄出來
$data = array();
while ($row = mysql_fetch_assoc($res, MYSQL_NUM)) {
$data[] = $row;
}
//隨機個數(shù),默認(rèn)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);
//純手寫的,不明白可以問我,記得給分
不用從頁面取id
去掉foreach
$sql="select * from phome_ecms_wma order by rand() limit 30"
就行了
/**
* MySQL 隨機取記錄
*
* @param $t 表
* @param $c ID列,默認(rèn)為id
* @param $n 取多少個
* @param $w 條件語句
* @param $f bool 是否強制以多維數(shù)組形式返回,默認(rèn)false
* @return array 取1個直接返回結(jié)果數(shù)組(除非$f為true),取1個返回多維數(shù)組,用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;
}
}
$sql = "select * from table";
$result = mysql_query($sql);
$rand = mt_rand(0,mysql_num_rows($result));
$i=0
while($rs = mysql_fetch_array($result)){
if($rand == $i){
$output = $rs[$i];
}
$i++;
}
$output數(shù)組就是隨機記錄