How can a PHP beginner effectively integrate PHP code into HTML for displaying database query results?
To effectively integrate PHP code into HTML for displaying database query results, beginners can use PHP's echo statement to output the results within the HTML structure. By fetching the data from the database using PHP and then echoing it within the HTML tags, the query results can be dynamically displayed on the webpage.
<?php
// Connect to the database
$conn = new mysqli('localhost', 'username', 'password', 'database');
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch data from the database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Display query results within HTML
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<div>";
echo "<p>Name: " . $row['name'] . "</p>";
echo "<p>Email: " . $row['email'] . "</p>";
echo "</div>";
}
} else {
echo "0 results";
}
// Close database connection
$conn->close();
?>