Foreach taking only the last record

Asked

Viewed 701 times

0

I’m developing a vendor registration screen, but my foreach is only getting the last record in a total of 3 records. What I might be doing wrong?

Below my code and attached to my screen. Thank you very much

<thead>

            <tr style="background-color: #CEF6EC">
              <th>ID</th>
              <th>Nome Fornecedor</th>
              <th class="d-none d-sm-table-cell">Contato</th>
              <th class="d-none d-lg-table-cell">Telefone</th>
              <th width="100" class="text-center">Ações</th>
            </tr>
          </thead>
          <tbody>

            <?php
            $sql = "SELECT id,nome,con,tel FROM cad_for ";

            $sql = $pdo->query($sql);

            If($sql->rowCount()>0){
              foreach($sql->fetchAll() as $fornecedor){
              }
            }
            ?>

            <tr>
              <td><?php echo $fornecedor\['id'\]; ?></td>
              <td><?php echo $fornecedor\['nome'\]; ?></td>
              <td class="d-none d-sm-table-cell"><?php echo $fornecedor\['con'\]; ?></td>
              <td class="d-none d-lg-table-cell"><?php echo $fornecedor\['tel'\]; ?></td>

              <td>
                <a href="visualizar.php?id=<?php echo $fornecedor\['id'\]; ?>" class="btn btn-outline-primary btn-sm" data-toggle="tooltip" data-placement="left" title="Visualizar"><i class="fas fa-eye"></i></a>
                <a href="editar.php?id=<?php echo $fornecedor\['id'\]; ?>" class="btn btn-outline-warning btn-sm" data-toggle="tooltip" data-placement="left" title="Editar cadastro"><i class="fa fa-fw fa-edit"></i></a>
              </td>
            </tr>
  • It worked out San! Thank you very much!

1 answer

1


Place the table row inside the loop foreach. Placing it after, will catch only the last result of the loop:

<?php
$sql = "SELECT id,nome,con,tel FROM cad_for ";

$sql = $pdo->query($sql);

If($sql->rowCount()>0){
  foreach($sql->fetchAll() as $fornecedor){
?>
<tr>
   <td><?php echo $fornecedor['id']; ?></td>
   <td><?php echo $fornecedor['nome']; ?></td>
   <td class="d-none d-sm-table-cell"><?php echo $fornecedor['con']; ?></td>
   <td class="d-none d-lg-table-cell"><?php echo $fornecedor['tel']; ?></td>
   <td>
      <a href="visualizar.php?id=<?php echo $fornecedor['id']; ?>" class="btn btn-outline-primary btn-sm" data-toggle="tooltip" data-placement="left" title="Visualizar"><i class="fas fa-eye"></i></a>
      <a href="editar.php?id=<?php echo $fornecedor['id']; ?>" class="btn btn-outline-warning btn-sm" data-toggle="tooltip" data-placement="left" title="Editar cadastro"><i class="fa fa-fw fa-edit"></i></a>
   </td>
</tr>
<?php
  }
}
?>

Browser other questions tagged

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