Using the Rand() function in PHP

David Carr

1 min read - 5th May, 2011

This tutorial introduces you to the function rand()

MySQL has many built in functions one of which is called rand() which is short for random. From time to time you might want to display some results from your database in a different order and here's where the rand() function comes into play.

For this example I will randomly show a different banner from my database.

Each time the page loads up I want a different banner to be shown and not in any order you would start with a normal select statement and then add rand() in an order by statement: <

$query ="SELECT * FROM banners ORDER BY RAND() LIMIT 1";
$result = mysql_query($query) or die("Problem, with Query:".mysql_error());

This would retrieve 1 banner as we have limited the results to 1 and the banner would be different each time as we have the order set to rand().

Random results may not always appear random as sometimes you may get the same results 2 or 3 times in a row, Other times you get a different result each time.

0 comments
Add a comment

Copyright © 2024 DC Blog - All rights reserved.