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 is the best method to select a random entry from a database table in PHP?
- How can the SQL query in PHP be optimized to retrieve the record with the highest ID from the database?
- In what scenarios would using a custom word wrapping function in PHP, like mb_wordwrap, be more beneficial than relying on built-in text formatting capabilities of web browsers, especially when considering different text encodings and display environments?