How can PHP code be optimized to efficiently output data from a MySQL database into an HTML table?
To efficiently output data from a MySQL database into an HTML table using PHP, it is important to minimize the number of queries and optimize the code for performance. One way to achieve this is by fetching all the data from the database in a single query and then looping through the results to populate the HTML table. Additionally, using prepared statements can help prevent SQL injection attacks and improve the security of the code.
<?php
// Establish a connection to the MySQL database
$connection = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($connection->connect_error) {
die("Connection failed: " . $connection->connect_error);
}
// Fetch data from the database
$sql = "SELECT * FROM table_name";
$result = $connection->query($sql);
// Output data into an HTML table
echo "<table>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row['id']."</td><td>".$row['name']."</td><td>".$row['email']."</td></tr>";
}
echo "</table>";
// Close the connection
$connection->close();
?>