PHP SQL Random

The PHP SQL Random is used to fetch data randomly from database in PHP. The Rand ( ) clause is used to fetch the random data from table into the browser.

PHP SQL Random

     

The PHP SQL Random is used to fetch data randomly from database in PHP. The Rand ( ) clause is used to fetch the random data from table into the browser. 

Understand with Example

The Tutorial illustrate an example from PHP SQL Random. To understand and elaborate the example we have a table 'users' that show the records of table 'users'.

 

 

Table: users

 

Source Code of sql_random.php

This example show you to fetch random data from database table. In this example we create select statement with ORDER BY RAND() clause in PHP. The RAND( ) clause is used to fetch data from table randomly.

<?php
  $con = mysql_connect("localhost","root","root");
  if (!$con){
  die('Could not connect: ' . mysql_error());
  }
  mysql_select_db("test", $con);

  $result = mysql_query("SELECT email FROM users ORDER BY RAND()");

  if (!$result) {
  echo 'Could not run query: ' . mysql_error();
  exit;
  }

  $row = mysql_fetch_array($result);
  echo "<b>Email: </b>";
  echo $row['email']."<br>";
?>

when we refresh  the browser, it  randomly  fetched the data from the table and display on the browser.  

Output:

Download Source Code

Advertisements

Ads

 

We have 1000s of tutorials on our website. Search Tutorials tutorials on our website.

Share on Google+Share on Google+

PHP SQL Random

Posted on: February 4, 2009 If you enjoyed this post then why not add us on Google+? Add us to your Circles

Advertisements

Ads
 

Discuss: PHP SQL Random  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments:2
Patrick Kershner
November 27, 2011
i want to use it as links how can i do that?

I would like to use this code to generate random search results from a recipe db, and want them to show up on the side bar. I have 7 slots i would like a random result to show up every time i visit the site, or visitor does. Is that possible?
Azeem Asim
January 18, 2012
Thanks...

Nice chunk of code. Helped me out... Thanks...

Ads

 

Ads