How do I adjust my date in my query?

5

$result_usuario = "SELECT * FROM vendas WHERE DATE(date_created) = '$data' AND 
tipo_venda = '$tipo_vendas' AND tipo = '$tipo_pagamento' ORDER BY 'id'";

I have this query, but it does not work right because the input that populates the variable '$ data' comes with the format '12 / 11/2018 'and the format that counts in the colon' date_created 'and' 2018-12 -11 ', how do I adjust my query ??

    
asked by anonymous 12.12.2018 / 19:57

3 answers

6

There are several ways to do this. I recommend the following:

// Recebe a variável com a data, e cria um objeto DateTime a partir do formato especificado.
$objetoData = DateTime::createFromFormat('d/m/Y', $data);

// Reformata a data do jeito desejado
$data = $objetoData->format('Y-m-d');

Then just use the $data variable the way you were doing it.

    
12.12.2018 / 20:14
6

Use a function that will serve two inputs dd/mm/YYYY ou YYYY-mm-dd .

function inverteData($data){
    if(count(explode("/",$data)) > 1){
        return join("-",array_reverse(explode("/",$data)));
    }elseif(count(explode("-",$data)) > 1){
        return join("/",array_reverse(explode("-",$data)));
    }
}

$data = "12/11/2018";

//para usar na query
$dataInvertida = inverteData($data); //2018-11-12

//alguma data retornada do select
$dataBanco = "2018-11-21";

$dataBancoInvertida =  inverteData($dataBanco); // 21/11/2018

example on ideone

$result_usuario = "SELECT * FROM vendas WHERE DATE(date_created) = '$dataInvertida' AND 
tipo_venda = '$tipo_vendas' AND tipo = '$tipo_pagamento' ORDER BY 'id'";
    
12.12.2018 / 20:40
4

Since you only need to make the query, you can bring your column date_created of the formatted select as needed.

DATE_FORMAT(date_created, '%d/%m/%y')

Here has more information about the date_format

It is possible to do through PHP as well.

Transforming the date you receive into the pattern used by the DB.

$dataFormat = DateTime::createFromFormat('d/m/Y', $data);

And to use afterwards you can format it to the required pattern

$data = $dataFormat->format('Y-m-D');
    
12.12.2018 / 20:14