foreach PHP and HTML table

2

I am programming in PHP and MySQL and I want to fill a simple table HTML with a query. I have problems with foreach , this is my code:

<table>
        <tr>
            <th>CODIGO</th>
            <th>DESCRIPCION</th>
            <th>GRUPO</th>
            <th>SECCION</th>
            <th>VIGENTE</th>
        </tr>
        <?php
        if (isset($_POST["btnBuscar"])) {
             $codigo = $_POST['txtCodigo'];
             $ser->codigoservicio = $codigo;
             $data = $sDriver->getByCodigo($codigo);
             //print_r($data);
            if(!empty($data)){
                    foreach ($data as $item) { ?>
                      <tr>
                        <td><?php echo $data->codigoservicio; ?></td>
                        <td><?php echo $data->descripcion; ?></td>
                        <td><?php echo $data->grupo; ?></td>
                        <td><?php echo $data->codigoseccion; ?></td>
                        <td><?php echo $data->vigente; ?></td>
                      </tr>     
        <?php       
            }
         ?>
        </table>
        <?php 
            }else{
                echo 'No hay resultados.';
            }
        }   
        ?>

This shows me the results but it repeats them 5 times each, and if I use:

<td><?php echo $item->codigoservicio; ?></td>

I get the following error:

  

Notice: Trying to get property of non-object in C: \ xampp \ htdocs ...

print_r($data);

Return me:

OaServicio Object ( 
                   [codigoservicio] => 12 
                   [grupo] => 3 
                   [descripcion] => prueba 
                   [codigoseccion] => 1 
                   [vigente] => 1 
                  )

How can I do?

    
asked by daniel 29.06.2016 в 22:25
source

2 answers

5

I'll leave the following script, I hope it works:

 if(!empty($data)){
 $tds = ""; //Inicmaos variable tds
 foreach ($data as $i=>$v) {  //Iteramos tu objeto
    $tds .= "<td>".$v."</td>"; // Extraemos solo el valor concatenandolo en la variable $tds.
 }
 echo "<tr>".$tds."</tr>"; // Imprimimos el resultado final
    
answered by 29.06.2016 в 22:52
1

In view of what you show you should not use a foreach because you can directly access the elements, you can do the following and you will get a single row:

<table>
<tr>
  <th>CODIGO</th>
  <th>DESCRIPCION</th>
  <th>GRUPO</th>
  <th>SECCION</th>
  <th>VIGENTE</th>
</tr>
<tr>
  <td><?php echo $data->codigoservicio; ?></td>
  <td><?php echo $data->descripcion; ?></td>
  <td><?php echo $data->grupo; ?></td>
  <td><?php echo $data->codigoseccion; ?></td>
  <td><?php echo $data->vigente; ?></td>
</tr>
</table>

Now if you want to use the foreach you can do the following:

<table>
<tr>
  <th>CODIGO</th>
  <th>DESCRIPCION</th>
  <th>GRUPO</th>
  <th>SECCION</th>
  <th>VIGENTE</th>
</tr>
<tr>
  <?php foreach ($data as $item) { ?>
    <td><?php echo $item; ?></td>
  <?php } ?>
</tr>
</table>
    
answered by 29.06.2016 в 23:00