Skip to content
PHP Logo

How can PHP loops be utilized to display data from a SQL database in alternating columns in HTML tables?

To display data from a SQL database in alternating columns in HTML tables using PHP loops, you can achieve this by fetching the data from the database, iterating over the rows, and using a counter variable to determine which column the data should be displayed in. By checking if the counter is odd or even, you can alternate between columns in the HTML table.

php
<?php
// Assuming $conn is the database connection object

// Query to fetch data from the database
$sql = "SELECT * FROM your_table";
$result = $conn->query($sql);

// Check if there are rows returned
if ($result->num_rows > 0) {
    echo "<table>";
    echo "<tr><th>Column 1</th><th>Column 2</th></tr>";

    $counter = 1;

    // Output data of each row
    while($row = $result->fetch_assoc()) {
        echo "<tr>";
        if ($counter % 2 == 1) {
            echo "<td>".$row["column1"]."</td>";
            echo "<td>".$row["column2"]."</td>";
        } else {
            echo "<td>".$row["column2"]."</td>";
            echo "<td>".$row["column1"]."</td>";
        }
        echo "</tr>";
        $counter++;
    }
    echo "</table>";
} else {
    echo "0 results";
}
$conn->close();
?>