Generate report between two dates with php and mysqli

Asked

Viewed 164 times

1

I’ve been racking my brain for a while, and I need help. I have a code that retrieves a date from the comic book and compares the days difference from that date to today.

If this difference is less than 7 the weekly record receives a value and if it is less than 30 the monthly receives a value.

Follows the code:

    $total_litros_semanal = 0;
  $total_litros_mensal = 0;

    $now = time(); // Data atual

    $abastecimento = "SELECT * from abastecimento ";
    $abastecimento .= "WHERE id_secretaria = '1'"; //mudar conforme o id da secretaria
    $query = mysqli_query($conexao,$abastecimento);
    if(!$query) {
      die("Falha na consulta ao banco");
    }
    while ($exibir = mysqli_fetch_array($query)) {
      $your_date = strtotime($exibir["data_abastecimento"]);
      $datediff = $now - $your_date;
      $diferenca = round($datediff / (60 * 60 * 24));
      if($diferenca<=30){
        $total_litros_mensal += $exibir["quantidade_litros"];
      }
      if($diferenca<=7){
        $total_litros_semanal += $exibir["quantidade_litros"];
      }
    }

The only problem is that with this code I take the last 7 days and in case I want to add only if we have started a new week, ie from Sunday starts a new week.

If the day is before the last Sunday it does not add, only if it is this week, same thing for the month.

If the date is in the previous month then does not add, however, I am tied in how to do this.

Obs: am using php + Mysqli procedural.

Hugs.

1 answer

1

If it helps, you can check the day of the week, and add a if checking if it’s Sunday, I used something similar for a vacancy system.

I will post a code below ve if it helps, in case I try not to do with your logic.

echo 'Proximo dia util: '. date('d/m/Y', strtotime('+1 day')) ."<br>";
$domingo = 0;
$segunda =1;
$terça =2;
$quarta=3;
$quinta=4
$sexta = 5;
$sabado = 6;// sabado 6ºdia - fim da semana


$tx=0;
$ty=0;

$dia_atual=date('w'); //pego o dia atual
$data_atual = date('d/m/Y'); //armazena a data atual
$dias = $sabado - $dia_atual;//verifica quantos dias falta pro sabado

if ($dia_atual == $sexta){
    $data_next = date('d/m/Y', strtotime('+3 day'));
}else if ($dia_atual == $sabado){
    $data_next = date('d/m/Y', strtotime('+2 day'));
}else if ($dia_atual == $domingo or $dias > 0){
    $data_next = date('d/m/Y', strtotime('+1 day'));
}

$inicio = strtotime("-$dia_atual days");
$fim = strtotime("+$dias days");
$ini_sem =date('d/m/Y',$inicio); //data inicial DIA UTIL(domingo)
$fim_sem = date('d/m/Y',$fim); //data final PROXIMO DIA UTIL(sabado)
  • Thanks buddy, I understood your logic, I just couldn’t implement the idea to my case, I’ll keep trying

Browser other questions tagged

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