How do you adjust my query date?

Asked

Viewed 85 times

4

$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 doesn’t work right because the input that fills the variable '$data' comes with the format '12/11/2018' and the format that counts in the colona 'date_created' and '2018-12-11', as I do to adjust my query??

3 answers

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 in ideone

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

5


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 variable $data the way you were doing.

4

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

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

Here has more information about the function date_format


It is possible to do through PHP as well.

Turning the date you receive into the default used by BD.

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

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

$data = $dataFormat->format('Y-m-D');

Browser other questions tagged

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