Home > Backend Development > PHP Tutorial > PHP如何随机读取数据库一条记录?

PHP如何随机读取数据库一条记录?

PHPz
Release: 2020-09-04 17:14:57
Original
3507 people have browsed it

PHP随机读取数据库几条记录的方法:首先找出数据表中所有记录的总数;然后在总数范围内使用“mt_rand()”函数选择一个随机数;最后从数据库中请求选中的随机数对应的那一行记录即可。

PHP如何随机读取数据库一条记录?

PHP如何随机读取数据库一条记录?

先找出数据表中所有记录的总数,并在总数范围内选择一个随机数,然后再从数据库中请求选中的随机数对应的那一行记录。

 <?php
           $sth = $dbh ->query("SELECT COUNT(*) AS count FROM quotes");
          
           if ($row = $sth ->fetchRow()){
          
                   $count = $row[0];
           } 
           else{
                die($row->getMessage());
           }
           
            $random = mt_rand(0,$count - 1);
           
            $sth = $dbh ->query("SELECT quote FROM quotes LIMIT $random,1");
           
            while($row = $sth ->fetchRow()){
           
                print $row[0]."\n";
            }
          ?>
Copy after login

以上代码片段先找到数据表中记录的总数,并在该范围内计算一个随机数,然后使用LIMIT $random 1来到数据表中从$random位置开始查询(SELECT)一行记录。
还有另一种可能的解决方法,如果使用的是MySQL 3.23或以上的版本,可以这样来做:

 <?php
            $sth = $dbh ->query(&#39;SELECT quote FROM quotes ORDER BY RAND() limit 1&#39;);
           
            while($row = $sth ->fetchRow()){
           
                prinf $row[0]."\n";
            }
          ?>
Copy after login

 这种情况下,MySQL会随机化记录行的排列顺序,然后返回第一行记录。

更多相关知识,请访问 PHP中文网!!

Related labels:
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
Latest Issues
php data acquisition?
From 1970-01-01 08:00:00
0
0
0
PHP extension intl
From 1970-01-01 08:00:00
0
0
0
How to learn php well
From 1970-01-01 08:00:00
0
0
0
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template