Thursday, April 30, 2009

Displaying Random records from MySQL database table


Sometimes we may need to display some value selected from database table which is having many records. In this situation we can select them randomly to improve user experience. It applies to displaying random advertisements, testimonials, quotes,images,background colors and news.

php is having a function rand() for getting random number within a range. Syntax is shown below.

int rand ( int $min , int $max )

Sample code is shown below.

$sqlbanner="select * from table_name
$recbanner=mysql_query($sqlbanner);
$rows=mysql_num_rows($recbanner);
$rand=rand(0,$rows-1);
$page_text=mysql_result($recbanner,$rand,'page_text');


We can use RAND() function of MySQL also to achieve this.

For example below code will select 10 random rows from the mysql table.

SELECT * FROM <table name> where <condition> ORDER BY RAND() LIMIT 10
More Articles...

No comments:

Search This Blog