Open In App

How to Display Recent Posts in DOM using PHP and MySQL ?

Last Updated : 03 Jun, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

Many times, we are very familiar with “latest blogs” or “recent posts” in the websites. So now, here is a simple solution for displaying the recent blogs on the DOM by using PHP and MySQLi.

Requirements:

  1. Database and tables
  2. XAMPP Server
  3. Editor (VS Code in this article).

Note: The bootstrap required in the code can be downloaded from Bootstrap Download. Add the required files in your HTML or PHP codes as shown below.

Code Snippet: The following code snippet shows how to add the required libraries in your respective HTML or PHP codes.




<head
 <link rel="stylesheet" 
  bootstrap/4.3.1/css/bootstrap.min.css"> 
</head
<body
  
<script src="
   integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/
   Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous">
</script
<script src="
   4.5.2/js/bootstrap.min.js">
</script
</body>


Requirements:

  1. MySQL Database and tables.
  2. XAMPP Server ( To download – Download server )
  3. Editor (VS Code was used in this article).

Steps to follow:

  1. Create a database with table “posts” having “id” and the contents needed to be displayed in the page.
  2. Steps to create a table in phpmyadmin tool:
    • Go to phpmyadmin
    • Login with your username as “root” and password as “”.
    • In the home page of phpmyadmin, click on *new* from the left sidebar to create a new database.

    • Give a name for the Database.

    • For Create Table, give a name for the table with the number of columns for it.

    • Give the column names and respective sizes or lengths.

    • Go to the insert tab, and insert the values to be stored.(This is just an example)

    Add the values to be displayed.

    posts table

  3. Create a PHP page named posts.php and place the folder inside the htdocs folder inside XAMPP.

    HTML Code: Download the font-awesome directory into your working folder and refer the appropriate location for the file “font-awesome.min.css” as shown below.

    HTML




    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      
    <head>
        <meta charset="utf-8">
        <meta name="viewport" content=
            "width=device-width, initial-scale=1">
      
        <link rel="stylesheet" href="
            crossorigin="anonymous">
      
        <!--Font Awesome-->
        <link rel="stylesheet" href="
        path/to/font-awesome/css/font-awesome.min.css">
        <!--Stylesheet-->
        <link href="style.css" rel="stylesheet" />
      
        <link rel="stylesheet" href="
    </head>
      
    <body>
      
        <!-- Blog Latest -->
        <div class="blog-latest">
            <div class="container">
                <h1 class="blog-secondary-heading text-dark">
                    Latest Blogs
                </h1>
      
                <div class="main-carousel p-2 " 
                    id="latestCarousel">
      
                    <div class="carousel-cell p-2">
                        <div class="card  mx-2" 
                            style="width: 18rem;">
                            <img class="card-img-top" 
                                src="img/1.jpg" 
                                alt="Card image cap">
                            <div class="card-body">
      
                                <h5 class="card-title">
                                    <a href="blog-template.php" 
                                    class="blog-link">
                                        CAT 1
                                </h5>
                                </a>
                                <h6 class="card-subtitle 
                                    mt-2 text-muted">
                                    The domestic cat is a member 
                                    of the Felidae,a family that 
                                    had a common ancestor about 
                                    10–15 million years ago. The 
                                    genus Felis diverged from the 
                                    Felidae around 6–7 million 
                                    years ago.
                                </h6>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
      
        <!-- Bootstrap -->
            integrity=
    "sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
            crossorigin="anonymous">
        </script>
          
        <script src=
            integrity=
    "sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
            crossorigin="anonymous">
        </script>
      
        <script src=
            crossorigin="anonymous">
        </script>
          
        <script src="
        </script>
    </body>
      
    </html>

    
    

    CSS code snippet: The following “style.css” file is used in the above code for styling of HTML controls.




    *{
      box-sizing: border-box;    
    }
      
    .card {
        height: 40%;
    }
      
    a.blog-link {    
        color:black;
        text-decoration:none;
    }
      
    a.blog-link:hover {    
        color: #adadad;
    }
      
    .column {
        float:left;
        width:15%;
        padding:2px;
        height:100px;
    }
      
    .row:after {
        content: "";
        display: table;
        clear: both;
    }

    
    

    Output:

    Single Post Here

  4. Now, we have to connect to the database and retrieve the “id” and hence all the details corresponding to it are added in the DOM. For this, we will use the MySQL queries.
    Here, we first sort the database by using the timestamp, using “order by” clause followed by pushing the id of the latest blog in an array followed by other id’s in the file “retrieve_id.php“.

    PHP




    <?php
       
    $servername = "localhost";
    $username = "root";
    $password = "";
    $db= "latest";
       
    $conn = mysqli_connect($servername, $username, $password, $db);
       
    if (!$conn) {
      die('Could not connect: ' . mysqli_error());  
    }
      
    /* To sort the id and limit the post by 4 */
    $sql = "SELECT * FROM posts ORDER BY timestamp desc limit 4 "
    $result = $conn->query($sql);
    $sqlall= "SELECT * FROM posts ORDER BY timestamp desc";
    $resultall = $conn->query($sqlall);
       
    $i = 0;
       
    if ($result->num_rows > 0) {  
      
        // Output data of each row
        $idarray= array();
        while($row = $result->fetch_assoc()) {
            echo "<br>";  
            
            // Create an array to store the
            // id of the blogs        
            array_push($idarray,$row['id']); 
        
    }
    else {
        echo "0 results";
    }
    ?>

    
    

  5. Change the “posts.php” file and include the above “retrieve_id.php” in it. Place the card inside a loop which will run until a number according to how many posts you want to display. Using the MySQL queries, retrieve the values from the DB table using the “id” array created in “retrieve_id.php“.

    Place the PHP code or the variables having values retrieved from the database in the HTML code wherever needed.

    Final Code: It is the combination of all the above steps and codes.

    PHP




    <?php 
    include 'retrieve_id.php'
    ?>
      
    <!DOCTYPE html>
    <html lang="en" dir="ltr">
      
    <head>
      <meta charset="utf-8">
      <meta name="viewport" content=
        "width=device-width, initial-scale=1">
      <title>Posts</title>
      
      <link rel="stylesheet" href="style.css">
      
      <link rel="stylesheet" href=
        crossorigin="anonymous">
      
      <!--Font Awesome-->
      <link rel="stylesheet" href=
    "path/to/font-awesome/css/font-awesome.min.css">
      
      <link rel="stylesheet" href=
    </head>
      
    <body>
      <!-- Blog Latest -->
      
      <div class="blog-latest">
        <div class="container">
          <h1 class="blog-secondary-heading text-dark">
            Latest Blogs</h1>
      
          <div class="main-carousel p-2 " 
            id="latestCarousel">
            <div class="row">
      
              <?php 
                  
                for($x = 0; $x < 4; $x++) {
      
                  // This is the loop to display all
                  // the stored blog posts
                  if(isset($x)) {
                    $query = mysqli_query(
    $conn,"SELECT * FROM `posts` WHERE id = '$idarray[$x]'");
                      
                    $res = mysqli_fetch_array($query);
       
                    $image = $res['img'];
                    $blog_title = $res['title'];
                    $blog_text = $res['text'];
                    $blog_id = $res['id'];
              ?>
              <div class="column">
                <div class="carousel-cell p-2">
                  <div class="card  mx-2" style="width: 18rem;">
                    <img class="card-img-top" src=
                      "<?php echo $image; ?>" alt="Card image cap">
                    <div class="card-body">
                      <h5 class="card-title">
                        <a href="blog-template.php" class="
                                    blog-link">
                          <?php 
                             echo $blog_title;
                        ?>
                      </h5>
                      </a>
                      <h6 class="card-subtitle mt-2 text-muted">
                        <?php 
                        echo $blog_text;
                      ?>
                      </h6>
                    </div>
                  </div>
                </div>
              </div>
              <?php
                  }
                 }
               ?>
            </div>
          </div>
        </div>
      </div>
      
      <!-- Bootstrap -->
      <script src="
    https://code.jquery.com/jquery-3.5.1.slim.min.js" 
        integrity=
    "sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous">
      </script>
      
      <script src=
        integrity=
    "sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous">
      </script>
        
      <script src=
        crossorigin="anonymous">
      </script>
        
      <script src=
      </script>
    </body>
      
    </html>

    
    

    Final Output:

    Recently added posts



Similar Reads

How to Undo the Most Recent Local Commits in Git?
When working with Git, it's common to make mistakes or realize that recent commits need to be revised. Whether you've made an error in your code, committed sensitive information, or simply want to restructure your commits, knowing how to undo the most recent local commits is an essential skill. This guide will walk you through the process of undoin
3 min read
How to like multiple posts on facebook news feed automatically using JavaScript ?
In this article, we are going to learn how to like multiple posts automatically on the Facebook news feed. Many a time we waste too much time liking all the posts in our news feeds. So this script will help to reduce our time and effort by automating this task. Approach: Make a variable post that points to an array of all the posts on the current p
2 min read
What is the difference between display: inline and display: inline-block in CSS?
The display property in CSS is a very useful and commonly used property that contains many values. The display property defines how an HTML element should be displayed on the webpage. The property also specifies the type of box used for an HTML element and how it should be laid out on the page. If we need to display the elements that are laid out a
4 min read
What is the difference between display:inline-flex and display:flex in CSS ?
In this article, we will see the display property &amp; its values, i.e. the inline-flex &amp; flex, in order to specify the display behavior of an element, along with understanding their basic differences &amp; will illustrate them through the examples. Both CSS display: inline-flex and display: flex properties are used to create flexible layouts.
3 min read
How to create the best Google My Business Posts ?
Post is something that visually represents your ideas, thoughts on a particular topic. As Digital Marketing is expanding with the expansion of technology and uses of social and the internet. Companies are looking forward to using this for better results. Every marketing company advertises its product through posts or blogs. For the better SEO ratin
6 min read
WordPress Publish Posts
WordPress is a free and open-source Content Management System (CMS) framework i.e. it is a tool that organizes the whole process of creating, storing and showcasing web content in an optimal way. WordPress started its journey as an improvement tool to enhance the regular typography of day-to-day writing. But it was taken as a blogging tool and as w
2 min read
WordPress Delete Posts
WordPress is an open-source Content Management System that is totally based on PHP and MySql which is used to create a dynamic website. Matt Mullenweg developed WordPress and Written in PHP language. WordPress is one of the most popular interfaces that allow users to customize and manage the website from its back-end content management system. It i
2 min read
WordPress Edit Posts
WordPress is a free and open-source Content Management System (CMS) framework. it is a tool that organizes the whole process of creating, storing, and showcasing web content in an optimal way. WordPress started its journey as an improvement tool to enhance the regular typography of day-to-day writing. But it was taken as a blogging tool and as we r
2 min read
WordPress Preview Posts
WordPress is an open-source Content Management System framework. it is a tool that organizes the whole process of creating, storing, and showcasing web content in an optimal way. WordPress started its journey as an improvement tool to enhance the regular typography of day-to-day writing. But it was taken as a blogging tool and as we reach the last
2 min read
How to add a video in WordPress Posts or Pages ?
WordPress is an open-source Content Management System and an interface that is totally based on PHP and MySql which is used to create a dynamic website. Matt Mullenweg developed WordPress and Written in PHP language. WordPress is one of the most popular interfaces that allow users to customize and manage the website from its back-end content manage
3 min read