How to verify that a date is in a range of dates with PHP and MYSQLI?

0

I'm working on a section where I have to filter photos depending on the data they enter in the inputs. The inputs I have are:

  • 1 input text for the title
  • 2 inputs date to set a date range for the photos
  • 1 input to select the country

The fact is that when collecting the data and making the following query:

$sentencia = "SELECT fichero, titulo, fecha, pais FROM fotos WHERE titulo LIKE '%$titulo%' OR fecha >= STR_TO_DATE('$desde', '%Y %m %d') AND fecha <= STR_TO_DATE('$hasta', '%Y %m %d') OR pais = '$pais'";

PROBLEM: I have placed some example dates in the inputs of the dates to check the correct functioning, but what happens is that it brings back all the photos, even those with the date = NULL in the database.

Can someone help me? Thanks.

    
asked by owenjr 23.11.2017 в 03:28
source

1 answer

0

We are going to answer you in two parts. On the one hand the SQL The logical operator OR , will return all the records that comply with ANY of the conditions that you put in the clause WHERE .

The logical operator AND will return all the records that meet ALL the conditions that you put in the clause WHERE

With what, according to what you have put, the most normal in your sentence SQL would be

$sentencia = "SELECT fichero, titulo, fecha, pais FROM fotos WHERE (titulo LIKE '%$titulo%') AND (fecha >= STR_TO_DATE('$desde', '%Y %m %d') AND fecha <= STR_TO_DATE('$hasta', '%Y %m %d')) AND (pais = '$pais')";

I have placed the parentheses in each condition so that the scope of each condition is better seen.

Regarding the question of your comment , I would personally make a dynamic query based on the fields filled by your user with the logical operator AND

    
answered by 23.11.2017 / 08:35
source