Home > php教程 > php手册 > body text

php随机取mysql记录方法示例

WBOY
Release: 2016-05-25 16:37:55
Original
1543 people have browsed it

在php中要随机取mysql记录我们可以直接使用mysql_query来执行mysql中的select rand函数获取的数据并读出来,下面我来给大家介绍一下具体实例.

方法一,代码如下:

select * from tablename order by rand() limit 1
Copy after login

把 limit 后面的数值改为你想随机抽取的条数,这里只取一条.

方法二,代码如下:

$query= "SELECT count(*) as count FROM recommends"; 
.... 
$max_num = $row['count']; // 取记录总数 
srand((double)microtime()*1000000); // 随机数种子 
$se_pos = rand(0, $max_num); // 随机数范围 
$length = 6; // 记录条数 
if (($max_num - $se_pos) <= $length) { 
$se_pos = $max_num - $se_pos; // 记录数不足6条的情况 
}
$query = "SELECT * FROM recommendsn limit ".$se_pos.",".$length;
Copy after login

例3,假设有一个名为xyj的数据库,库中有表obj,表中有一字段为name,现在要实现从表里随机选取一条记录,具体程序如下:

<?php
$db = mysql_connect("localhost", "root");
mysql_select_db("xyj", $db);
$result = mysql_query("SELECT * FROM obj", $db);
$max_num = mysql_num_rows($result); //取得数据库的记录数
srand((double)microtime() * 10000000); //生成随机数种子。
$se_pos = rand(0, $max_num - 1); //从0到最大记录数取随机数
$length = 30; //设定共取多少条记录
//下面是取出指定数目的记录。
$result_lim = mysql_query("select * from obj limit $se_pos,$length", $db);
$myrow_lim = mysql_fetch_array($result_lim);
printf("%sn", $se_pos); //显示随机得到的记录号
printf("%sn", $myrow_lim["name"]); //显示随机得到的记录的name字段
Copy after login


永久地址:

转载随意~请带上教程地址吧^^

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template