Skip to content
PHP Logo

How can data from a database be displayed in 3 columns per row in PHP?

To display data from a database in 3 columns per row in PHP, you can fetch the data from the database and then loop through the results, displaying each item in a table with 3 columns per row. You can use a counter variable to keep track of the number of columns displayed and start a new row after every third column.

php
<?php
// Fetch data from the database
$result = mysqli_query($connection, "SELECT * FROM your_table");

// Display data in 3 columns per row
echo "<table>";
$counter = 0;
while ($row = mysqli_fetch_assoc($result)) {
    if ($counter % 3 == 0) {
        echo "<tr>";
    }
    echo "<td>" . $row['column_name'] . "</td>";
    $counter++;
    if ($counter % 3 == 0) {
        echo "</tr>";
    }
}
echo "</table>";
?>