Home Sql Mysql-example PHP SQL Random
Questions:Ask|Latest

 
 

Share on Google+Share on Google+

PHP SQL Random

Advertisement
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

Advertisement

If you enjoyed this post then why not add us on Google+? Add us to your Circles



Liked it!  Share this Tutorial


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: February 4, 2009

Related Tutorials

Ask Questions?    Discuss: PHP SQL Random  

Post your Comment


Your Name (*) :
Your Email :
Subject (*):
Your Comment (*):
  Reload Image
 
 
Comments
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...
DMCA.com