1Hund TV
1Hund TV

Reputation: 7

How to create table in foreach

This is my php code

    <?php
include_once 'conectDB.php';
$sql ='SELECT CHECKLISTS.USER_ID, CHECKLISTS.ADMIN_ID, PROGRAMS.PROGRAM_NAME
FROM CHECKLISTS
LEFT JOIN COMPUTERS
ON CHECKLISTS.USER_ID = COMPUTERS.COMPUTER_NAME
LEFT JOIN ADMINS
ON CHECKLISTS.ADMIN_ID = ADMINS.USER_ID
LEFT JOIN CHECKLIST_PROGRAMS
ON CHECKLISTS.ID = CHECKLIST_PROGRAMS.CHECKLIST_ID
LEFT JOIN PROGRAMS
ON PROGRAMS.ID = CHECKLIST_PROGRAMS.PROGRAM_ID
';

$result = $connection->query($sql);
$checklists = array();
if ($result->num_rows > 0){

  while($row = $result->fetch_assoc()) {

    $checklists [] = $row;
  }

} else {
  echo '0 results';
}
$connection->close();
?>

And this is HTML CODE in this foreach I don't know how to query and create table :(

<html>
<head>
  <link rel="stylesheet" type="text/css" href="bootstrap/css/bootstrap.min.css">
  <title>C.I.G. Check List</title></head>
  <body>
    <div class="container">
      <div class="row" style="margin-top:10px;">
        <div class="col-md-offset-2 col-md-8">
          <div class="row" style="margin-top:20px;">
          <div class="col-md-4"><h3>C.I.Gruop Checklist</h3></div>
          <div class="col-md-6" style="margin-top:19px; font-size:20px;"><a href="Addchecklist.php">New Item</a></div>
        </div></div>
      </div>
      <div class="col-md-2"></div>
      <div class="row" style="margin-top:20px;">
        <div class="col-md-offset-1 col-md-9">
          <!-- ส่วนแสดงผล -->
          <?php
          foreach ($checklists as $checklist) {
            print_r($checklist);
          }
          ?>
        </div>

      </div>

</div
  </body>
  </html>

Upvotes: 0

Views: 485

Answers (3)

Miguel Jim&#233;nez
Miguel Jim&#233;nez

Reputation: 514

One option can be:

<table>
  <? foreach ($checklists as $checklist) { ?>
  <tr>
    <td>
      <? echo $checklist; ?>
    </td>
  </tr>
  <? } ?>
</table>

Within the loop, everything you write is repeated as many times as the checklist items

Upvotes: 0

Saani
Saani

Reputation: 782

Creating table in foreach is simple. Try this:

<table>
    <thead>
        <tr>
            <th>Check List</th>
        </tr>
    </thead>
    <tbody>
        <?php
        foreach ($checklists as $checklist) {
            ?>
            <tr>
                <?php


                echo "<td>" . $checklist . "</td>";
                ?>

            </tr>
            <?php
        }
        ?>
    </tbody>
</table>

Upvotes: 0

D.k
D.k

Reputation: 462

You need to do like this:-

<table>
<?php
    foreach ($checklists as $checklist) {
        echo '<tr><td>'.$checklist.'</td></tr>';            
    }
?>
</table>

Upvotes: 1

Related Questions