How to bypass table tags that are inside the foreach in PHP and HTML

Asked

Viewed 922 times

2

I need to assemble a schedule of days and events. When one of the days of the event is equal to the day of the table, it has to appear on the screen in the correct place. I’m already being able to compare and show, however, because the table is completely disassembled because of the algorithm that searches and traverses, I can’t make the table right ever!

Someone would know a solution to be able to mount the table by dribbling these tags?

Follow the code of the table:

<table class="table table-bordered">
    <thead>
        <tr>
          <th><center>Turno \ Dia</center></th>
          <?php
            include_once 'classes/semestresclass.php';

            if(!isset($_SESSION)) {session_start();} 

            $idSemestre = $_SESSION['SemestreGeral'];

            $oSemestre = new semestresclass();
            $oSemestre -> listarEdicao($idSemestre);  

            $array = mysql_fetch_array($oSemestre->retorno());

            $start_date = $array['DataDeInicio'];
            $end_date = $array['DataDeTermino'];

            $inicio = new DateTime($start_date);
            $fim = new DateTime($end_date);
            $fim->modify('+1 day');

            $interval = new DateInterval('P1D');
            $periodo = new DatePeriod($inicio, $interval ,$fim);

            foreach($periodo as $data){
                echo '<th><p><center>'.$data->format("d/m/Y").'</p><p>'.$data->format("l").'</p></center></th>';

                include_once 'classes/bancasclass.php';

                if(!isset($_SESSION)) {session_start();}  

                $idSemestre = $_SESSION['SemestreGeral'];

                $oBanca = new bancasclass();
                $oBanca -> listar ($idSemestre);   

                while ($arrayBancas = mysql_fetch_array($oBanca->retorno())){
                    if (date('Y-m-d', strtotime($arrayBancas['dataHora'])) == $data->format('Y-m-d')) {
                       echo '<td>teste</td>';
                    }
                } 
            }
          ?>
    </table>

In this scheme I will also have schedules to organize this table... I’m trying to go in pieces, solve the day first and then the time, but maybe I’m going the wrong way, maybe I have to do everything together... In this case, the first column on the left will take the shifts 'morning', 'afternoon' and 'night' and, depending on the time of the event, put it according to the two axes.

I’m trying with a table, but solutions without table are also welcome!!

Table: inserir a descrição da imagem aqui

  • 2

    How should the table be presented? The way you explained it is a bit confusing.

  • The idea was to make a table like the one I put there as an image, where the data would be inserted in the respective places, according to the day and time...

  • I have not read the whole code but I assume it is enough to put <tr> before "while" and </tr> right at the end of the code, still inside the "foreach", because the foreach is what iterates the rows and while iterates the columns. But it has nonsense like the <tr> opened up there and there is no closure.. You must close it before the foreach. This first <tr></tr> I think should be the header, so inside it put the "static" part that is the days of the week (mon, Tue, Wed...).

  • 1

    That answer, despite seem much more of what you need, can be of great value to you who, apparently, has not adopted (yet?) a template engine

2 answers

5


You have some issues to address so you can solve your problem. The information below will not solve your whole problem, but aims to create the basis so that you can handle the same:

Opening and closing of tags

You have to have some attention to the opening and closing of tags because they have to be closed in the reverse order to which they were opened:

echo '
<th>
  <p>
    <center>'.$data->format("d/m/Y").'</p>
    <p>'.$data->format("l").'</p>
  </center>
</th>';

Should be:

echo '
<th>
  <center>
    <p>'.$data->format("d/m/Y").'</p>
    <p>'.$data->format("l").'</p>
  </center>
</th>';

The best way is to always have the indented code because it makes it easier to read it and you realized more quickly of problems like this.

Or <td> with text or <td> empty, but always <td>

To Markup of <table> has to be present in its entirety except some exceptions where we make use of the attributes colspan or rowspan. For this reason, whether or not you have a check that will generate a <td>, you’ll have to have a fallback for a <td> empty so as not to break the layout table:

if (date('Y-m-d', strtotime($arrayBancas['dataHora'])) == $data->format('Y-m-d')) {
    echo '<td>teste</td>';
}

Should be:

if (date('Y-m-d', strtotime($arrayBancas['dataHora'])) == $data->format('Y-m-d')) {
    echo '<td>teste</td>';
}
else{
    echo '<td></td>';
}

Thus, if there is a match on date, will be sent to browser to <td>teste</td>, if not, a <td> empty, thus avoiding breaking the layout table.

Output is per row and not per column

Everything you have within this cycle is working as if the output for the browser is per column, but actually the output is per line because the browser reads the code from top to bottom and not from left to right:

foreach ($periodo as $data) {
  // dados devem ser trabalhados por "row"
}

Likewise, within the cycle above, you’re:

  • Insert the file consecutively bancasclass.php;
  • Consecutively calling the function session_start();

I don’t know why this is happening, but you’re supposed to call session_start() once at the beginning of your file, unless for some reason you are destroying the session within the bancasclass.php. Similarly, the file bancasclass.php should be called once and the code present in it should be used within the cycle if necessary. Since the file is called ...class.php, it is assumed that you have a class.

At last, your cycle while() is sending <td> to the browser, but the <td> must be inside a <tr>. Analyzing together with the image you placed, you’re supposed to have 7 (seven) <td> within each <tr>, being the first with the text "Morning", "Afternoon", or "Night"...

Given all this, and the fact that we don’t know what’s in your file bancasclass.php, it is assumed that the same processes data that depend directly on your cycle foreach(), I suggest the following adaptation to the code:

// Para guardar o HTML do cabeçalho da tabela
$cabecalhosHtml = '';

// Para guardar o HTML das linhas do corpo da tabela
$linhasHtml = '';

foreach ($periodo as $data) {

  /* Processar cabeçalho da coluna
   */
  $cabecalhosHtml.= '
  <th style="text-align:center;">
    '.$data->format("d/m/Y").'
    <br>
    '.$data->format("l").'
  </th>';

  /* Processar celulas da coluna
   */
  include_once 'classes/bancasclass.php';

  if (!isset($_SESSION)) { session_start(); }

  $idSemestre = $_SESSION['SemestreGeral'];

  $oBanca = new bancasclass();
  $oBanca -> listar ($idSemestre);   

  // abrir linha da tabela
  $linhasHtml.= '<tr>';

  // processar celunas da linha
  while ($arrayBancas = mysql_fetch_array($oBanca->retorno())) {

    if (date('Y-m-d', strtotime($arrayBancas['dataHora'])) == $data->format('Y-m-d')) {
      $linhasHtml.= '<td>teste</td>';
    }
    else {
      $linhasHtml.= '<td></td>';
    }
  }

  // fechar linha da tabela
  $linhasHtml.= '</tr>';
}

echo $cabecalhosHtml;
echo $linhasHtml;

2

You have to consider all table tags when printing values. From what I have seen do not have the tags correctly, inspect the generated HTML, in browser, and see the result. You will find that you are missing tags and so the table is not right.

Each row of the table has to start with <tr> and end with </tr>, or when you are printing lines in a cycle for You have to print those tags every time you change your line.

Here’s a basic example of how you can have a table:

<table border="1" style="width:300px">
    <thead>   <!-- Inicio do cabeçalho -->
        <tr>    <!-- Inicio de linha     -->
            <th> 
                Nome
            </th>
            <th>
                Sobrenome 
            </th>
            <th>
                Telefone
            </th>
        </tr>   <!-- fechar linha de cabeçalho -->
    </thead>    <!-- fechar cabeçalho          -->
    <tbody>     <!-- inicio do corpo da tabela -->
        <tr>    <!-- Inicio de linha           -->
            <td>
                João
            </td>
            <td>
                Silva
            </td>
            <td>
                912345678
            </td>
        </tr>      <!-- Fim de linha -->
        <tr>
            <td>
                Juliana
            </td>
            <td>
                Sobral
            </td>
            <td>
                912345677
            </td>
        </tr>
    </tbody>
    <tfoot>
        <tr>
            <td>
                Total
            </td>
            <td>
                Total
            </td>
            <td>
                Total
            </td>
        </tr>
    </tfoot>
</table>

Browser other questions tagged

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