How can PHP developers effectively handle and display database query results in HTML output without compromising security or performance?
When displaying database query results in HTML output, PHP developers should use prepared statements to prevent SQL injection attacks. To ensure performance, developers can limit the number of records fetched from the database and paginate the results. Additionally, developers should sanitize and validate user input to prevent cross-site scripting attacks.
<?php
// Establish a database connection
$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);
}
// Prepare and execute a SQL query
$stmt = $conn->prepare("SELECT id, name FROM users WHERE status = ?");
$status = "active";
$stmt->bind_param("s", $status);
$stmt->execute();
$result = $stmt->get_result();
// Display the query results in HTML
echo "<table>";
while ($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row['id'] . "</td><td>" . $row['name'] . "</td></tr>";
}
echo "</table>";
// Close the database connection
$stmt->close();
$conn->close();
?>