How to Get Last Month Data in PHP MySQL?

Feb 18, 2022 . Admin

Hello Friends,

I am going to explain you example of how to get last month data in PHP?. You will learn PHP query to get months data. I would like PHP select data last of month. This article will give you simple example of PHP query to get last months record.

We will use get search how to select last months data from table using PHP. You can understand a concept of search how to take last month data from the current month in PHP. So, we can illustrate the getting a data last months in the PHP.

You can see both example of how do I get last months data in PHP.

Table: users


So, let's see bellow solution:

index.php
<?php

$servername = "localhost";
$username = "root";
$password = "root";
$dbname = "db_php";

// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);

$sql = "SELECT 
            * 
        FROM `users` 
        WHERE DATE(created_at) >= DATE_ADD(LAST_DAY(DATE_SUB(NOW(), INTERVAL 2 MONTH)), INTERVAL 1 DAY)
           AND DATE(created_at) <= LAST_DAY(DATE_SUB(NOW(), INTERVAL 1 MONTH))";

$result = $conn->query($sql);

while ($row = $result->fetch_assoc()) {
    echo '<pre>';
    print_r($row);
}

?>
Output:
Array
(
    [id] => 1
    [name] => Nikhil Thumar
    [email] => nikhil@gmail.com
    [created_at] => 2022-01-08 10:19:31
    [updated_at] => 2022-02-11 10:21:30
)
It will help you...
#PHP