Error comparing PHP-MySQL dates

1

I have the following code:

HTML:

<input name="dataInicio" type="text" class="form-control datepicker" placeholder="Data" maxlength="10" autocomplete="off" />
<input name="dataFim" type="text" class="form-control datepicker" placeholder="Data" maxlength="10" autocomplete="off" />

MySQL

'date' DATE NOT NULL,

PHP

$dataInicio = (isset($_POST['dataInicio'])) ? '2017-09-25' : date("Y-m-d", strtotime($_POST['dataInicio']));
$dataFim = (isset($_POST['dataFim'])) ? date("Y-m-d") : date("Y-m-d", strtotime($_POST['dataFim']));

And finally the test I'm doing to return the range of days I need:

PHP

SELECT date,time,resultCode,hostname,user,sites,qt_acessos,bytes
                FROM tblResumo
                WHERE 
                    date >= '$dataInicio' AND 
                    date <= '$dataFim'

But I have the return of ALL the records, regardless of the date entered in the application form! And what I do not understand is that by checking in the POST, the values entered for the date range are there correctly. I am printing the values as JSON, if this information is useful. Where am I going wrong? I anticipate my thanks.

    
asked by anonymous 09.10.2017 / 22:56

2 answers

1

There is a problem in defining the variables $dataInicio and $dataFim . The ternary operator returns '2017-09-25' and date("Y-m-d") if exists data in the corresponding $_POST item.

I suppose you want to fill in '2017-09-25' or date("Y-m-d") (today) if does not exist data in the $_POST array. Therefore, using !isset() :

$dataInicio = (!isset($_POST['dataInicio'])) ? '2017-09-25' : date("Y-m-d", strtotime($_POST['dataInicio']));
$dataFim = (!isset($_POST['dataFim'])) ? date("Y-m-d") : date("Y-m-d", strtotime($_POST['dataFim']));
    
10.10.2017 / 00:01
1

There is a field of type date in html:

<input type="date">

This will standardize the information passed in the field, instead of being validated later if it is all numbers for example.

In SELECT you can use the SQL command BETWEEN :

This command takes values between past param- eters, such as dates. Example:

SELECT * FROM tabela WHERE data BETWEEN '2017-01-01' AND '2017-01-31';

Note: There is a Jquery UI function called a datepicker where you can optimize the entire date field.     

09.10.2017 / 23:50