0

In this code I am converting date format dd-mm-yy to yy-mm-dd. When I echo $from date it gives the correct date (2017-6-1). Similarly with echo $to. But when I echo the query it can't get value of $from, but $to it gets the date correctly. What is the problem with $from?

Here is my code...

<script language='javascript'>
    jQuery(function($)
           { 
               $("#from").datepicker({ dateFormat: 'dd-mm-yy' });
               $("#to").datepicker({ dateFormat: 'dd-mm-yy' });
           });
</script>

<input name="from" id="from" type="text" />
<input name="to" id="to" type="text" />

<?php
    $froms = $_POST['from'];
    list($day, $month, $year) = explode("-", $froms);
    $from = "$year-$month-$day";

    $too = $_POST['to'];
    list($day, $month, $year) = explode("-", $too);
    $to = "$year-$month-$day";

    if($from = "$year-$month-$day" && $to = "$year-$month-$day")
    {
        echo "select * from students where (enquiry_date between '$from' and '$to')";
    }
?>

Result:

select * from students where (enquiry_date between '1' and '2017-06-09') order by student_id
toonice
  • 2,211
  • 1
  • 13
  • 20
kevin
  • 234
  • 2
  • 14
  • 2
    `if($from = "$year-$month-$day" && $to = "$year-$month-$day")` Quite sure you wanted to use `==` instead of `=` Also you should think about your IF statement again. IMO it doesn't make any sense, even with double `==` – Twinfriends Jun 02 '17 at 06:22
  • I am trying this @Twinfriends but query does't echo. – kevin Jun 02 '17 at 06:28
  • It doesn't display because your if statement doesn't make any sense. I don't think its "true" - so it simply skips that part. – Twinfriends Jun 02 '17 at 06:32

2 Answers2

4

First of all, you need to use '==' instead of '=' when you are comparing.

Otherwise, I think you are trying to check if the date format is entered correctly.

If so, replace line:

if($from = "$year-$month-$day" && $to = "$year-$month-$day")

with this line:

if(validateDate($from) && validateDate($to))

and make sure you define the function validateDate:

function validateDate($date)
{
    $d = DateTime::createFromFormat('Y-m-d', $date);
    return $d && $d->format('Y-m-d') == $date;
}

function was copied from this answer or php.net

Glavić
  • 42,781
  • 13
  • 77
  • 107
Maleka
  • 90
  • 1
  • 9
0

User PHP Date funtion for date formating:

<?php
    $froms = $_POST['from'];
    $from = date('Y-m-d', strtotime($froms));

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

    echo "select * from students where (enquiry_date between '".$from."' and '".$to."')";
?>
Govind Samrow
  • 9,981
  • 13
  • 53
  • 90