How can you efficiently output data from a MySQL table in a formatted HTML table using PHP?
To efficiently output data from a MySQL table in a formatted HTML table using PHP, you can fetch the data from the database, loop through the results, and dynamically generate the HTML table rows and columns. This can be achieved by using PHP's MySQLi or PDO extension to connect to the database, execute a query to fetch the data, and then loop through the results to output them in a formatted HTML table.
<?php
// Connect to MySQL database
$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);
}
// Fetch data from MySQL table
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Output data in HTML table format
if ($result->num_rows > 0) {
echo "<table>";
// Output table headers
echo "<tr><th>Column 1</th><th>Column 2</th></tr>";
// Output table data
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row['column1']."</td><td>".$row['column2']."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
// Close MySQL connection
$conn->close();
?>
Keywords
Related Questions
- What are some common pitfalls when including multiple PHP files in a project?
- How important is it to adhere to coding standards like PSR-2 when developing PHP classes for specific data types like measurement values?
- What potential security risks are associated with embedding HTML code within PHP echo statements?