Kevin Heimlich Kevin Heimlich - 2 months ago 9
HTML Question

html table mixed up when echo from while loop

HTML Table getting mixed up when having echo in while loop. Bellow attached the output image for that. How can i get normal table with loop result? Please note i am getting table data by searching with manual date.

<?php
if (isset($_POST['submit_date'])) {
if (empty($_POST['m_date'])) {
echo '<div class="alert alert-danger">Error: Select date then search</div>';
}else{
$m_date = $_POST['m_date'];
$q = mysqli_query($conn, "SELECT * FROM bazar_dor WHERE m_date='$m_date'");
echo '<table style="width:100%">
<tr>
  <th>Category Name</th>
  <th>Price</th>
  </tr>
<tr>
';

while ($row=mysqli_fetch_array($q)) {
$cat_name = $row['cat_name'];
$price = $row['price'];
echo '<td>'.$cat_name.'</td><td>'.$price.'</td>';
}

echo '</tr></table>';

}
}
?>


the output i am getting from this code

Answer

It looks like you'll need to include table rows (<tr>) inside your loop, as well. Your current code outputs all data on the same row, which undoubtedly breaks the table.

echo '<table style="width:100%">
        <tr>
          <th>Category Name</th>
          <th>Price</th>
        </tr>';

while ($row=mysqli_fetch_array($q)) {
  $cat_name = $row['cat_name'];
  $price = $row['price'];
  echo '<tr><td>'.$cat_name.'</td><td>'.$price.'</td></tr>';
}

echo '</table>';