In this post, you will be learning how to filter or find the data between two dates in php mysql which means you will be Selecting Data Between Two Dates in PHP/MySQL.
First, we will create a html form with two input fields as type=date and one submit button to submit the form. On Submit of form you will be searching the data from database between two dates and show them in a html table format which will be designed with Bootstrap v5 (Version 5).
So guys, lets get started to filter or find the data between two dates in php mysql STEP by STEP:
Note: For better and detailed understanding. please watch out the Video above.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Funda of Web IT</title>
<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/css/bootstrap.min.css" rel="stylesheet">
</head>
<body>
<div class="container">
<div class="row justify-content-center">
<div class="col-md-12">
<div class="card mt-5">
<div class="card-header">
<h4>How to Filter or Find or Get data (records) between TWO DATES in PHP</h4>
</div>
<div class="card-body">
<form action="" method="GET">
<div class="row">
<div class="col-md-4">
<div class="form-group">
<label>From Date</label>
<input type="date" name="from_date" value="<?php if(isset($_GET['from_date'])){ echo $_GET['from_date']; } ?>" class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>To Date</label>
<input type="date" name="to_date" value="<?php if(isset($_GET['to_date'])){ echo $_GET['to_date']; } ?>" class="form-control">
</div>
</div>
<div class="col-md-4">
<div class="form-group">
<label>Click to Filter</label> <br>
<button type="submit" class="btn btn-primary">Filter</button>
</div>
</div>
</div>
</form>
</div>
</div>
<div class="card mt-4">
<div class="card-body">
<table class="table table-borderd">
<thead>
<tr>
<th>ID</th>
<th>First Name</th>
<th>Last Name</th>
</tr>
</thead>
<tbody>
<?php
$con = mysqli_connect("localhost","root","","phptutorials");
if(isset($_GET['from_date']) && isset($_GET['to_date']))
{
$from_date = $_GET['from_date'];
$to_date = $_GET['to_date'];
$query = "SELECT * FROM users WHERE created_at BETWEEN '$from_date' AND '$to_date' ";
$query_run = mysqli_query($con, $query);
if(mysqli_num_rows($query_run) > 0)
{
foreach($query_run as $row)
{
?>
<tr>
<td><?= $row['id']; ?></td>
<td><?= $row['firstname']; ?></td>
<td><?= $row['lastname']; ?></td>
</tr>
<?php
}
}
else
{
echo "No Record Found";
}
}
?>
</tbody>
</table>
</div>
</div>
</div>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.js"></script>
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.0-beta1/dist/js/bootstrap.bundle.min.js"></script>
</body>
</html>