Home  >  Article  >  Backend Development  >  Example of how to randomly pick mysql records in php_PHP tutorial

Example of how to randomly pick mysql records in php_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 17:06:48981browse

To randomly select mysql records in php, we can directly use mysql_query to execute the data obtained by the select rand function in mysql and read it out. Let me introduce you to a specific example.

Method 1:

The code is as follows
 代码如下 复制代码

  select * from tablename order by rand() limit 1 

Copy code

select * from tablename order by rand() limit 1

 代码如下 复制代码

$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;

Change the value after limit to the number of records you want to randomly select. Only one is taken here.

Method 2:


$query= "SELECT count(*) as count FROM recommends"; ....
The code is as follows

Copy code
 代码如下 复制代码

$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字段

$max_num = $row['count']; // Get the total number of records srand((double)microtime()*1000000); // Random number seed

$se_pos = rand(0, $max_num); //Random number range

$length = 6; //Number of records $se_pos = $max_num - $se_pos; // When the number of records is less than 6 } $query = "SELECT * FROM recommendsn limit ".$se_pos.",".$length; Example 3
Suppose there is a database named xyj. There is a table obj in the database. There is a field in the table called name. Now we want to randomly select a record from the table. The specific procedure is as follows:
The code is as follows Copy code
Statement:
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