What is the best practice for displaying MySQL data in a visible table using PHP?
When displaying MySQL data in a visible table using PHP, it is best practice to fetch the data from the database, loop through the results, and output them in an HTML table format. This can be achieved by using PHP's MySQLi or PDO extension to connect to the database, execute a query to retrieve the data, and then iterate over the results to display them in a table structure.
<?php
// Connect to MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");
// Check connection
if ($mysqli->connect_error) {
die("Connection failed: " . $mysqli->connect_error);
}
// Query to fetch data from database
$sql = "SELECT * FROM table_name";
$result = $mysqli->query($sql);
// Display data in a table format
echo "<table border='1'>";
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 connection
$mysqli->close();
?>
Keywords
Related Questions
- Are there any best practices or specific syntax requirements when setting email headers in PHP to ensure successful delivery?
- How can CSS be used to display the weekday in uppercase in a PHP function?
- What are the benefits of using DateTime over traditional date functions in PHP for date manipulation?