What best practices should be followed when using PHP to display database data in a table format?
When displaying database data in a table format using PHP, it is important to properly sanitize the data to prevent SQL injection attacks. Additionally, you should use prepared statements to securely interact with the database. It is also recommended to separate your HTML markup from your PHP logic for better readability and maintainability.
<?php
// Connect to database
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
// Prepare and execute query
$stmt = $pdo->prepare("SELECT * FROM mytable");
$stmt->execute();
// Display data in a table format
echo "<table>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
while ($row = $stmt->fetch(PDO::FETCH_ASSOC)) {
echo "<tr><td>{$row['id']}</td><td>{$row['name']}</td><td>{$row['email']}</td></tr>";
}
echo "</table>";
?>