Skip to content
PHP Logo

How can PHP developers efficiently display data from a MySQL database in separate div elements in a repeating pattern?

To efficiently display data from a MySQL database in separate div elements in a repeating pattern, PHP developers can fetch the data from the database using a query, loop through the results, and output each record within a div element. By using a combination of PHP and HTML, developers can dynamically generate div elements for each record in the database, creating a visually appealing and organized display of the data.

php
<?php
// Connect to MySQL database
$connection = mysqli_connect("localhost", "username", "password", "database");

// Check connection
if (!$connection) {
    die("Connection failed: " . mysqli_connect_error());
}

// Fetch data from database
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);

// Display data in div elements
if (mysqli_num_rows($result) > 0) {
    while ($row = mysqli_fetch_assoc($result)) {
        echo "<div>";
        echo "<h2>" . $row['title'] . "</h2>";
        echo "<p>" . $row['description'] . "</p>";
        echo "</div>";
    }
} else {
    echo "No records found";
}

// Close database connection
mysqli_close($connection);
?>