Find specific day of the week between dates

3

I have the following code to post to a calendar days and times available and for this I use the following routine:

    //recebo dados do formulario
    //inclusive o dia da semana ex.: Friday
    $dia_semana = $_POST['dia_semana'];
    $hora = $_POST['hora']; 
    $laboratorio = $_POST['laboratorio'];
    $quantidade = $_POST['quantidade']-1;

    //pega a data de hoje
    //para verificar qual a proxima data correspondente ao
    //dia enviado pelo formulario
    // como por exemplo, proxima sexta(Friday)
    $hoje = date('Y-m-d');
    $dia = date("Y-m-d", strtotime("$hoje next $dia_semana"));

        $dados = array(
            'data' => $dia,
            'hora' => $hora,
            'laboratorio' => $laboratorio
        );
        //cadastra no banco a primeira data usando minha funcao
        $cadastrar = DBCreate('nw_vip',$dados);

      //faz um loop para cadastrar as proximas datas
      //com o dia escolhido limitado a quantidade
      //passada pelo formulario
      for($i=0;$i<$quantidade;$i++)
      {
       //se a primeira sexta caiu no dia 10
       //caucula as proximas somando 7 dias e cadastrando
       $dia =  date("Y-m-d", strtotime("$dia +7 day"));
       $dados = array(
         'data' => $dia,
         'hora' => $hora,
         'laboratorio' => $laboratorio
       );
      //cadastra no banco usando e minha função
      $cadastrar = DBCreate('nw_vip',$dados);
}

My problem if I post 5 Fridays today and then post another 5 Fridays, it will repeat the dates.

So I would need it the second time I was to release it I could consider the last sixth already registered if there is any and register from it.

Example: Launch 3 Fridays at 8 o'clock:

Sex 24/06 8:00
Sex 01/07 8:00
Sex 08/07 8:00

If I post again later, 5 more than the next one will continue from Friday the 6th. How to make an appointment to know the date of the last Friday already registered, according to my example. Of course it could be another day and another time.

    
asked by anonymous 23.06.2016 / 16:10

1 answer

3

You can make a query in your table by looking for the last occurrence of the day of the week that you are trying to schedule. For the example of Friday it looks like this:

SELECT MAX(data_agenda) AS ultima_data
  FROM minha_agenda
 WHERE WEEKDAY(data_agenda) = 5; 
/* semana iniciando em 0 para domingo, então 5 é sexta-feira, ok? */

You can change the query to WHERE to see more restrictions , such as time, laboratory, or any other information you wish.

The result of the query will always be the last date in its context. If empty means that you have not yet registered and can start with your own day informed by the user.

Information about the WEEKDAY function here: link

Note : You can also use the DAYOFWEEK , which uses the week pattern started at 1 for Sunday, 2 for Monday, and so on.

    
23.06.2016 / 16:23