0

I am trying to print all my data to an html table, which works, but only for the first table row.

My PHP code:

    $data = "";
while ($row = mysqli_fetch_assoc($result)) {
   $data = "<tr>
                <td>" . $row['name'] . "</td>
                <td>" . $row['email'] . "</td>
                <td>" . $row['message'] . "</td>
                <td>" . $row['created'] . "</td>
            </tr>";
 }

My html code:

<!DOCTYPE html>
<html>
<body>

<table border="1">
    <tr>
        <th width="15%">Name</th>
        <th width="15%">Email</th>
        <th width="50%">Message</th>
        <th width="20%">Created</th>
    </tr>
    <?= $data ?>
</table>

</body>
</html>

How can I make the table automatically insert more rows, and the MySQL data?

Both these codes are in 1 php file.

3 Answers 3

1

It looks to me that you're resetting $data to the latest row for each iteration of your while loop, instead of adding new html and data to that variable. Instead use:

$data .= "<tr..."
Sign up to request clarification or add additional context in comments.

Comments

1
$data = "<tr>
            <td>" . $row['name'] . "</td>
            <td>" . $row['email'] . "</td>
            <td>" . $row['message'] . "</td>
            <td>" . $row['created'] . "</td>
        </tr>";

becomes

$data .= "<tr>
            <td>" . $row['name'] . "</td>
            <td>" . $row['email'] . "</td>
            <td>" . $row['message'] . "</td>
            <td>" . $row['created'] . "</td>
        </tr>";

Comments

0

Instead of

$data = "<tr>

use

$data.= "<tr>

which means you are appending all the tr in the loop

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.