Skip to content
PHP Logo

How can PHP be used to display database entries in a specific layout on a webpage?

To display database entries in a specific layout on a webpage using PHP, you can retrieve the data from the database using SQL queries and then loop through the results to display them in the desired format on the webpage. You can use HTML and CSS to structure and style the layout as needed.

php
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";

$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Retrieve data from the database
$sql = "SELECT * FROM table";
$result = $conn->query($sql);

// Display data in a specific layout
if ($result->num_rows > 0) {
    while($row = $result->fetch_assoc()) {
        echo "<div>";
        echo "<h2>" . $row["title"] . "</h2>";
        echo "<p>" . $row["content"] . "</p>";
        echo "</div>";
    }
} else {
    echo "0 results";
}

// Close the connection
$conn->close();
?>