scrshot
scrshot

Reputation: 1

How Can I Put While Loop SQL Results in A Table in PHP?

I'm trying to put the results of an SQL query inside of a table and everytime theres a new result to make a new table data box. My code looks like

<html>
<style>
table {
  font-family: arial, sans-serif;
  border-collapse: collapse;
  width: 100%;
}

td, th {
  border: 1px solid #dddddd;
  text-align: left;
  padding: 8px;
}
</style>
<?php
<table style="width:100%">
<tr>
     <th>
          message
     </th>
</tr> 
while ($row = $resultSet->fetch_assoc()) {
    echo "<td>" . $row['message'] . "</td>";   
}
?>

But it makes a new box horizontally. How can I make it vertical and how can I also make it so it works for more than just one th element?

Upvotes: 0

Views: 366

Answers (2)

M. Eriksson
M. Eriksson

Reputation: 13635

You need to add <tr>'s (which indicates new rows in your table)

while ($row = $resultSet->fetch_assoc()) {
    echo '<tr>';
    echo '<td>' . $row['message'] . '</td>';   
    echo '</tr>';
}

If you want to use more <th>'s, then you need to add more <td>'s.

<table style="width:100%">
<tr>
     <th>
          message
     </th>
     <th>
         foo
     </th>
</tr> 
while ($row = $resultSet->fetch_assoc()) {
    echo '<tr>';
    echo '<td>' . $row['message'] . '</td>';   
    echo '<td>' . $row['foo'] . '</td>';   
    echo '</tr>';
}
?>
</table>

<th> and <td> are for setting columns and <tr> are for setting rows. So just make sure you have the same number of <th>'s and <td>'s.

I would recommend that you read up on how HTML tables work.

Upvotes: 1

Alex Stoneham
Alex Stoneham

Reputation: 76

wrapp a <tr> short for table row around your <td> table data.

while ($row = $resultSet->fetch_assoc()) {
    echo "<tr><td>" . $row['message'] . "</td></tr>";   
}

Don't forget to end the table after the loop if thats what you want to do.

Upvotes: 0

Related Questions