Compare current time to time recorded in the database?

Asked

Viewed 195 times

1

I have an hour registered in the database and would like to compare it with the current time. How should I do it with PHP?

The reason for this is that I needed to select a value that was available at a certain time.

The fields I have are:

  • Start time()
  • time-out()

And I needed you to select one of the values from the database that was within the hour.

  • which bank? you want to select in query or compare in code php?

  • You want to know if the current time is between the two times that are in the bank?

  • Yes, it is possible?

  • is yes, see if the answer I posted meets you

2 answers

2


I did it in a way that I did it alone.

First I looped through all the data in the table and proceeded to compare hours.

$select = mysqli_query($db, "SELECT * FROM programas");
while($mos2=mysqli_fetch_assoc($select)){
    $str_inicio=strtotime($mos2['hora_inicio']);
    $str_fim=strtotime($mos2['hora_fim']);
    $str_atual=strtotime($hora_toda);
    $diferenca=$str_fim-$str_atual;
    if($str_atual > $str_inicio && $str_atual < $str_fim){
        $variavel = $mos2['id'];
    }
}

With this, he will return what he has id which I wish to present.

$select2=mysqli_query($db, "SELECT * FROM programas where id = '".$variavel."'");
if(mysqli_num_rows($select2)){
$mos=mysqli_fetch_assoc($select2);

$radio = $mos['hora_inicio']." - ".$mos['hora_fim'];

echo $mos['img'].",".$mos['nome'].",".$radio.",".str_replace(" ", "_", $mos['nome']);
}

Note: The last echo is used personally later in the code so no explanation is needed.

1

In place of $inip and $fimp you must put the time that is in your database:

$QUERY = SELECT * FROM BANCO.TABELA;
$EXECUTE_QUERY = mysqli_query($conexao, $QUERY);
$DATA = mysqli_fecth_array($EXECUTE_QUERY);
$inip = $DATA['hora_inicio'];
$fimp = $DATA['hora_fim'];

$startP = $inip;
$endP   = $fimp;
$now    = time();//Hora atual

if($startP <= $now && $now <= $endP){
    echo "Dentro do horario";
} else {
    echo "Fora do horario";
}
  • the time format he questioned is time() which is an entire value.

  • @RFL had not attacked me to this, I think the above amendment should resolve then

Browser other questions tagged

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