This article mainly introduces the php method for randomly obtaining mysql records. it is a very practical technique and has some reference value for examples of several common methods for randomly obtaining mysql data, for more information about how to use php to randomly retrieve mysql records, see the examples in this article. Share it with you for your reference. The specific analysis is as follows:
To randomly retrieve mysql records in php, we can directly use mysql_query to execute and read the data obtained by the select rand function in mysql. here we will give you a brief introduction.
Method 1: The code is as follows:
The code is as follows:
Select * from tablename order by rand () limit 1
Change the value after limit to the number you want to randomly extract. here, only one value is used.
Method 2: The code is as follows:
The code is as follows:
$ Query = "SELECT count (*) as count FROM recommends ";
....
$ Max_num = $ row ['count']; // Retrieve the total number of records
Srand (double) microtime () * 1000000); // random seed
$ Se_pos = rand (0, $ max_num); // random number range
$ Length = 6; // number of records
If ($ max_num-$ se_pos) <= $ length ){
$ Se_pos = $ max_num-$ se_pos; // when there are less than 6 Records
}
$ Query = "SELECT * FROM recommendsn limit". $ se_pos. ",". $ length;
Example 3: assume that there is a database named xyj with the table obj in the database and the field name in the table. now we need to randomly select a record from the table. the specific procedure is as follows:
The code is 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); // Obtain the number of database records
Srand (double) microtime () * 10000000); // generates a random seed.
$ Se_pos = rand (0, $ max_num-1); // random number from 0 to the maximum number of records
$ Length = 30; // set the total number of records
// The following figure shows the specified number of records.
$ Result_lim = mysql_query ("select * from obj limit $ se_pos, $ length", $ db );
$ Myrow_lim = mysql_fetch_array ($ result_lim );
Printf ("% sn", $ se_pos); // display the random record number
Printf ("% sn", $ myrow_lim ["name"]); // display the name field of the random record
?>
I hope this article will help you with php programming.