Example of a php method for randomly retrieving mysql records

Source: Internet
Author: User
Tags random seed
To randomly retrieve mysql records in php, we can directly use mysql_query to execute and read the data obtained by The selectrand function in mysql. below I will introduce the specific instance to you. method 1: The code is as follows: sele... 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. next I will introduce the specific example.

Method 1: 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:

$ 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; // case where the number of records is less than 6} $ 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:

 


Permanent address:

Reprint at will ~ Please bring the tutorial URL ^

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.