在php中要随机取mysql记录我们可以直接使用mysql_query来执行mysql中的select rand函数获取的数据并读出来,下面我来给大家介绍一下具体实例.
方法一,代码如下:
select * from tablename order by rand() limit 1
把 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;
- }
-
- $query = "SELECT * FROM recommendsn limit ".$se_pos.",".$length;
例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);
-
- $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"]);
- ?>
|