Fetch Random rows records from Database Using Mysqli and PHP - Mostlikers

08 December, 2015

Fetch Random rows records from Database Using Mysqli and PHP

In this tutorial, you will learn various techniques to how to Fetch Random rows records from Database. Using this code you can display random gallery profile, Online examination random questions, multiple choice quiz system. I used following simple query for retrieving random records from database table.

Fetch Random rows records from Database Using Mysqli and PHP

Live Demo        Download

Select random rows in MySQL

SELECT * FROM table ORDER BY RAND()

RAND () - This SQL statement will retrieve the random record from the database.

Select random rows with limit in MySQL

SELECT * FROM table ORDER BY RAND() LIMIT 10


Sample Program

<?php
 $db=new mysqli('localhost','root','','database');
 $all_row=$db->query("SELECT * FROM products ORDER BY RAND() ");
?>
<html>
<body>
<?php if(isset($all_row) && is_object($all_row) && count($all_row)):?>
 <?php foreach ($all_row as $key => $product) { ?>        
 <div>
  <h3><?php echo $product['name']; ?></h3>
  <h4>$<?php echo $product['price']; ?> / month</h4>             
 </div>   
<?php } ?>
<?php endif; ?> 
</body>
</html>

Have a Question? Share your feedback below.

"You have to learn the rules of the game. And then you have to play better than anyone else. .  "
                                             
                                         - Albert Einstein








Related Topics

No comments:

Post a Comment