PHP random fetch MySQL Record Method Example

Source: Internet
Author: User
Tags rand

Method One:

The code is as follows Copy Code

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

$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


Suppose there is a database named Xyj, there are table obj in the library, there is a field name in the table, and now you want to select a random record from the list, the program is as follows:

  code is as follows copy code

<?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);//from 0 to maximum record number of random number

$length = 30;//Set total number of records

//Below is to take out a 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 a randomly obtained record number

printf ("%sn", $myrow _lim["name");//Displays the randomly obtained record's name field

Related Article

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.