Friday, February 16, 2018

Select 5 Random Records From MySQL Database and Display

This post explain how to retrieve random records from the MySQL database and display the same records in UI. you can use this technique to display Random Ads in your web pages. It is very easy and simple to use.
 40/5000 sélectionnez l'enregistrement aléatoire de la base de données mysql, select random record from mysql database



Use the Below MySQL statement to filter out random records from the "Post" Table ( select random record from database php mysql  ):

SELECT * FROM `post` ORDER BY RAND() LIMIT 5

Selecting random record from mysql database table in php

In this example we are retrieving 5 different post from MySQL database in random order and displaying the same records in "index.php" page. Here we are retrieving the post title, post details and post link  from the "POST" table. when you refresh the web page  that time, it will show different post records each time.



First Create "Post" Database Table
CREATE TABLE `post` (
  `POSTID` int(3) NOT NULL,
  `POSTTITLE` varchar(100) NOT NULL,
  `POSTDETAILS` varchar(10000) NOT NULL,
  `POSTLINK` varchar(100) NOT NULL
)

Once You have created above table, Then put the records in this table.

config.php
Consists of database configuration details to establish database connection.
<?php
/* DATABASE CONFIGURATION */
define('DB_SERVER', 'localhost');
define('DB_DATABASE', 'skptricksdemo');
define('DB_USERNAME', 'root');
define('DB_PASSWORD', '');

?>

controller.php
Controller work is to control the flow of execution. Here when you load and refresh page each time, controller handle the request and process the result.
<?php
include("PostDAOClass.php");

$PostClass = new PostClass();
echo $PostClass->displayData();

?>

PostDAOClass.php
This DAO class helps to establish the database connection and populate/fetch the records from MySQL database.
<?php
 include("config.php");
 Class PostClass{  
  
  // connect to mysql database... 
  public function DBConnect(){
   
   $dbhost = DB_SERVER; // set the hostname
   $dbname = DB_DATABASE ; // set the database name
   $dbuser = DB_USERNAME ; // set the mysql username
   $dbpass = DB_PASSWORD;  // set the mysql password
   
   try {
    $dbConnection = new PDO("mysql:host=$dbhost;dbname=$dbname", $dbuser, $dbpass); 
    $dbConnection->exec("set names utf8");
    $dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
    return $dbConnection;
    
   }
   catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
   }   
  }  
  
  // Display 5 random post from POST Table
  public function displayData(){      
   
   try {
    $dbConnection = $this->DBConnect();
    
    $stmt = $dbConnection->prepare('SELECT POSTLINK,POSTTITLE,POSTDETAILS FROM `POST` ORDER BY RAND() LIMIT 5');    
    $stmt->execute();    
    $Count = $stmt->rowCount();     
    
    if ($Count  > 0){
     while($data=$stmt->fetch(PDO::FETCH_ASSOC)) {           
      
      echo '<div id="display-post">
      <div id="post-header" > <a href="'.$data['POSTLINK'].'" >'.$data['POSTTITLE'].'</a></div>
      <div>  '.$data['POSTDETAILS'].'     </div>
      </div>';      
     }
    }    
   }
   catch (PDOException $e) {
    echo 'Connection failed: ' . $e->getMessage();
   } 
  }  
   
  
 } 
 
?>

index.php
This page fetch random records from the database and display the records in formated order.
<html lang="en">

<head>
    <style>
        body {
            background-color: #e5e5e5;
            margin: 40px auto;
            width: 600px;
        }
        #main-container {
            background-color: white;
            width: 500px;
            padding: 5px;
        }
        #display-post {
            margin-left: 10px;
            margin-bottom: 15px;
            border-top: 2px dotted black;
        }
        #post-header {
            font-size: 20px;
            font-weight: bold;
        }
        #display-post:first-child {
            border-top: none;
        }
    </style>
</head>

<body>
    <div id="main-container">

        <?php include( "controller.php"); ?>

    </div>
</body>

</html>

Download Link :
https://github.com/skptricks/php-Tutorials/tree/master/Select%205%20Random%20Records%20From%20MySQL%20Database%20and%20Display

This is all about Select Random Records in MySQL database. Thank you for reading this article, and if you have any problem, have a another better useful solution about this article, please write message in the comment section.


No comments:

Post a Comment