Error comparing PHP-Mysql dates

Asked

Viewed 135 times

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 interval 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 records, regardless of the date informed in my application form! And what I don’t understand is that by checking in the POST, the values reported for the date range are there correctly. I am printing the values as JSON if this information is useful. Where am I wrong? I anticipate my thanks.

2 answers

1

There is a field of the type date html:

<input type="date">

This will standardize the information passed in the field, rather than being valid later if it is all numbers for example.

In the SELECTyou can use the SQL command BETWEEN:

This command takes values between past parameters, such as dates. Example:

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

Obs: Exists in Jquery UI a function called datepicker where you can optimize the whole date field.

  • Thanks for the tip, man! I’ll switch to date. As to the datepicker, I already use it! I had a problem using the BETWEEN in SQL, for being several conditions in my WHERE, but still I thank you for the tips and attention! Hug.

1


There is a problem in your definition of variables $dataInicio and $dataFim. Ternary operator returns '2017-09-25' and date("Y-m-d") case exists data in item $_POST correspondent.

I imagine what you want is to fill with '2017-09-25' or date("Y-m-d") (today) case does not exist data in the array $_POST. 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']));
  • Wow, man! What a wobble, I forgot about the denial :( Thank you so much! Solved my problem here. I always had doubts with ternary operator and this only worsened when I did a test contrary $dataInicio = (isset($_POST['dataInicio'])) ? date("Y-m-d", strtotime($_POST['dataInicio'])) : '2017-09-25'; and I wasn’t returning anything. So I went to check now and actually there were no records. Anyway, thank you very much!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.