Currently seeking new career opportunities in web development, particularly with Laravel, Hire Me

Using the Rand() function in PHP

David Carr

Tutorials PHP & MySQL

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.

Laravel Modules Your Logo Your Logo Your Logo

Become a sponsor

Help support the blog so that I can continue creating new content!

Sponsor

My Latest Book

Modular Laravel Book - Laravel: The Modular way

Learn how to build modular applications with Laravel Find out more

Subscribe to my newsletter

Subscribe and get my books and product announcements.

Learn Laravel with Laracasts

Faster Laravel Hosting

© 2006 - 2024 DC Blog. All code MIT license. All rights reserved.