PHP & MySQL | Tutorials

David Carr

Using the Rand() function in PHP

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.

Domains are often purchased from multiple providers, keeping track of where a domain is and its DNS settings can be tricky. Domain Mapper solves this by listing all your domains in one place. View your DNS settings and receive reminders to renew your domains. Try it today.

Support my work by donating with PayPal.

Subscribe to my newsletter

Subscribe and get my books and product announcements.

© 2009 - 2021 DC Blog. All code MIT license. All rights reserved.