How to filter records by date with PHP

Algirdas Žarkaitis picture Algirdas Žarkaitis · Feb 28, 2018 · Viewed 8.9k times · Source

I have a working date filter with PHP. The problem is that if I don't filter my records then no records are shown and also I get this type of error:

Notice: Undefined index: dateFrom in ... on line 37

How can I make a date filter using PHP, so that if I don't add any dates to my filter it shows all records, and if I add dates to filter it shows only filtered records?

Here's my code:

HTML FORM enter image description here

<?php
    include('config/connect.php');
    $query=mysqli_query($connect,"SELECT * FROM tasks");
?>

<table>
    <tr>
        <th>Title</th>
        <th>Due Date</th>
        <th>Edit | View</th>
    </tr>

    <?php

    //GETTING VALUE FROM FILTER
    $new_date = date('Y-m-d', strtotime($_POST['dateFrom']));
    //echo $new_date;

    $new_date2 = date('Y-m-d', strtotime($_POST['dateTo']));
    //echo $new_date2;

    $dateFrom = date('Y-m-d', strtotime($_POST['dateFrom']));
    $dateTo = date('Y-m-d', strtotime($_POST['dateTo']));

    while($row=mysqli_fetch_array($query)){

    //FILTERING USING DATES
    if (($row['due_date'] > $dateFrom) && ($row['due_date'] < $dateTo)){
    ?>

    <tr>
        <td><?php echo  $row['title'] ?></td>
        <td><?php echo  $row['due_date'] ?></td>
        <td><a href="edit_task.php?id=<?php echo $row['id'];?>"> <button type="button">Edit</button> </a> | <a href="view_task.php?id=<?php echo $row['id'];?>"> <button type="button">View</button> </a></td>
    </tr>

    <?php }} ?>

</table>

Answer

Rahul picture Rahul · Feb 28, 2018

you need to change date('Y-m-d', strtotime($row['due_date'])); instead $row['due_date'] like this

if (date('Y-m-d', strtotime($row['due_date']))>$dateFrom && date('Y-m-d', strtotime($row['due_date'])) < $dateTo){

and you need to check variable first by isset(); your code should be like this

<?php
if (isset($_POST['dateFrom'])) {


    //GETTING VALUE FROM FILTER
    $new_date = date('Y-m-d', strtotime($_POST['dateFrom']));
    //echo $new_date;

    $new_date2 = date('Y-m-d', strtotime($_POST['dateTo']));
    //echo $new_date2;

    $dateFrom = date('Y-m-d', strtotime($_POST['dateFrom']));
    $dateTo = date('Y-m-d', strtotime($_POST['dateTo']));

    while($row=mysqli_fetch_array($query)){

    //FILTERING USING DATES
    if (date('Y-m-d', strtotime($row['due_date']))>$dateFrom && date('Y-m-d', strtotime($row['due_date'])) < $dateTo){
    ?>

    <tr>
        <td><?php echo  $row['title'] ?></td>
        <td><?php echo  $row['due_date'] ?></td>
        <td><a href="edit_task.php?id=<?php echo $row['id'];?>"> <button type="button">Edit</button> </a> | <a href="view_task.php?id=<?php echo $row['id'];?>"> <button type="button">View</button> </a></td>
    </tr>

    <?php }
} 

}
?>