This article summarizes the PHP random fetch MySQL record method. Share to everyone for your reference. The specific analysis is as follows:
In PHP to randomly fetch MySQL records we can directly use Mysql_query to execute the Select Rand function in MySQL to get the data and read it, here to give you a brief introduction.
Method One, the code is as follows:
Copy Code code as follows:
SELECT * FROM TableName ORDER by rand () limit 1
Change the value of the limit back to the number of bars you want to randomly extract, and take only one.
Method Two, the code is as follows:
Copy Code code as follows:
$query = "SELECT count (*) as Count from recommends";
....
$max _num = $row [' count ']; Total number of records taken
Srand (Double) microtime () *1000000); Random Number of seeds
$se _pos = rand (0, $max _num); Range of random numbers
$length = 6; Number of record bars
if (($max _num-$se _pos) <= $length) {
$se _pos = $max _num-$se _pos; In the case of less than 6 records
}
$query = "SELECT * from Recommendsn limit". $se _pos. ",". $length;
Example 3, assuming that there is a database named Xyj, there is a table obj in the library, there is a name in the table, and now you want to select a random record from the list, the following procedures are:
Copy Code code as follows:
<?php
$db = mysql_connect ("localhost", "root");
mysql_select_db ("Xyj", $db);
$result =mysql_query ("select * from obj", $db);
$max _num=mysql_num_rows ($result);//Get the number of records in the database
Srand (Double) microtime () *10000000); Generate random number of seeds.
$se _pos=rand (0, $max _num-1); Number of random numbers from 0 to Max Records
$length = 30; Set how many records to take together
The following is a specified number of records removed.
$result _lim=mysql_query ("select * from obj limit $se _pos, $length", $db);
$myrow _lim=mysql_fetch_array ($result _lim);
printf ("%sn", $se _pos);//display randomly obtained record number
printf ("%sn", $myrow _lim["name");//Display the Name field of a randomly obtained record
?>
I hope this article will help you with your PHP program design.