Are there any best practices for efficiently handling and displaying data from a MySQL table in an HTML format using PHP?
When handling and displaying data from a MySQL table in an HTML format using PHP, it is important to use proper coding practices to ensure efficiency and security. One best practice is to use prepared statements to prevent SQL injection attacks. Another best practice is to fetch and display data in chunks rather than all at once to improve performance. Additionally, using CSS for styling and separating PHP logic from HTML presentation can make the code more maintainable.
<?php
// Establish a connection to the MySQL database
$servername = "localhost";
$username = "root";
$password = "";
$dbname = "mydatabase";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Fetch data from MySQL table
$sql = "SELECT * FROM mytable";
$result = $conn->query($sql);
if ($result->num_rows > 0) {
// Output data in HTML table format
echo "<table>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>" . $row["column1"] . "</td><td>" . $row["column2"] . "</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>