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

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.

filter_none

edit
close

play_arrow

link
brightness_4
code

<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>

chevron_right


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

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <!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>

    chevron_right

    
    

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

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    *{
      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;
    }

    chevron_right

    
    

    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

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?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";
    }
    ?>

    chevron_right

    
    

  5. Change the “posts.php” file and include the above “retrieve_id.php” in it. Place the card inside a loop which will run untill 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

    filter_none

    edit
    close

    play_arrow

    link
    brightness_4
    code

    <?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>

    chevron_right

    
    

    Final Output:

    Recently added posts

full-stack-img




My Personal Notes arrow_drop_up

Check out this Author's contributed articles.

If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.