What is the best approach to search for results in HTML files based on database query results in PHP?
When searching for results in HTML files based on database query results in PHP, the best approach is to first retrieve the data from the database using a query, then loop through the results to generate HTML content dynamically. This can be achieved by using PHP to fetch the data from the database and then using HTML to display the results in a structured format on the webpage.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "dbname";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query the database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Display results in 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();
?>