Benjamin Oats Benjamin Oats - 1 month ago 6
HTML Question

print out rows from database in a table

Why do I need to use echo to print MYSQL data to my table?

Take a look at my code sample.

what I am trying to do

Select and show all data in the query in a table.

Problem 1

This works:

<td><?php echo "<br>". $row["testName"]. "<br>";?></td>


This does not:
<td><?php $row["testName"] ?></td>


I feel the second option should work but does not.

(not such a big deal just feels wrong)

Problem 2

I would also like all data to be in one table not for the loop to create a new table every time.

$sql = "SELECT testName, userID FROM `results` WHERE `userID` = '$something' ";
$result = $conn->query($sql);

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
?>

<table class="table table-hover">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>some text Score</th>
<th>Date Taken</th>
</tr>
</thead>
<tbody>
<tr>
<th scope="row">1</th>
<td><?php $row["testName"] ?></td>
<td><?php $row["userID"] ?></td>
<td><?php echo "<br>". $row["testName"]. "<br>";?></td>
</tr>
</tbody>
</table>
<?php
}
} else {
echo "0 results";
}

Answer

If you want to display value from database then you must need to use echo. because $row["testName"] contains some value but which value it is, that you can see after echoing it.

To display data in single table try below code:

    <?php 
$sql = "SELECT testName, userID FROM  `results` WHERE  `userID` = '$something' ";
      $result = $conn->query($sql); ?>
      <table class="table table-hover">
        <thead>
            <tr>
                <th>ID</th>
                <th>Name</th>
                <th>some text Score</th>
                <th>Date Taken</th>
            </tr>
        </thead>
    <?php

        if ($result->num_rows > 0) {
        // output data of each row
        while($row = $result->fetch_assoc()) {
    ?>
        <tr>
            <th scope="row">1</th>
            <td><?php echo $row["testName"] ?></td>
            <td><?php echo $row["userID"] ?></td>
            <td><?php echo "<br>". $row["testName"].  "<br>";?></td>
        </tr>

    <?php } ?> 
 </table>
   <?php }else 
       {
         echo "0 results";
        }