05May2011
Author
Dave
Category
PHP
Tags
, ,
Using the Rand() function in PHP Thumbnail

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.

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:

<?php
$query ="SELECT * FROM banners ORDER BY bannerID 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.

Author
Dave

About the Author

has written 72 articles on Dave is my name.

My name is David Carr I'm a PHP web developer based in Hull it is my passion to design and develop clean, accessible and usable websites using PHP and other web technologies, I'm an avid Twitter user why not follow me? https://twitter.com/daveismynamecom

Visit this author's website   ·   View more posts by

Sharing is caring.
  • Subscribe to our feed
  • Share this post on Delicious
  • StumbleUpon this post
  • Share this post on Digg
  • Tweet about this post
  • Share this post on Mixx
  • Share this post on Technorati
  • Share this post on Facebook
  • Share this post on NewsVine
  • Share this post on Reddit
  • Share this post on Google
  • Share this post on LinkedIn

Discussion

One response to "Using the Rand() function in PHP"

  • - Alen Air Purifiers says:

    I think the admin of this site is truly working hard in favor of his site, because here every data is quality based data.

Leave a Comment