Filter using combobox

Asked

Viewed 74 times

2

I’m trying to make some filters using combobox, these filters correspond to the year and month pulled from a date.

For example: When selecting the year 2019 and the month 01 all results for the month 2019 01 are returned and so on.

However, when I need to pull all results only from the year 2019 to know the amount of overall result of the year without selecting the month is not shown any results.

Can someone give me a north how to solve this problem

Follows excerpt from the codes

NOTE: the data field is in date format, I am using mysql

<?php

$parametro_ano = filter_input(INPUT_GET, "parametro_ano");
$parametro_mes = filter_input(INPUT_GET, "parametro_mes");

$sql = "SELECT data_processo FROM tb_processo
 WHERE MONTH (data_processo) = $parametro_mes and YEAR (data_processo) = $parametro_ano";

?>

<div class="row">
  
    <select name="parametro_ano" class="form-control">
      <option value="">SELECIONE O ANO</option>
      <option value="2019">2019</option>
      <option value="2018">2018</option>
      <option value="2017">2017</option>
    </select><br><br>
 
    <select name="parametro_mes" class="form-control">
      <option value="">SELECIONE O MES</option>
      <option value="01">01</option>
      <option value="02">02</option>
      <option value="03">03</option>
      <option value="04">04</option>
      <option value="05">05</option>
      <option value="06">06</option>
      <option value="07">07</option>
      <option value="08">08</option>
      <option value="09">09</option>
      <option value="10">10</option>
      <option value="11">11</option>
      <option value="12">12</option>
    </select>
</div><br>

1 answer

1


I believe the solution below will solve your problem, but I suggest you do some validations.

$parametro_ano = filter_input(INPUT_GET, "parametro_ano");
$parametro_mes = filter_input(INPUT_GET, "parametro_mes");

$sql = "SELECT data_processo FROM tb_processo WHERE 1=1";
if (isset($parametro_mes)) {
    $sql .= " AND MONTH (data_processo) = $parametro_mes";
}

if (isset($parametro_ano)) {
    $sql .= " AND YEAR (data_processo) = $parametro_ano";
}

Browser other questions tagged

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