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
- In what ways can outdated code from tutorials impact the functionality and security of a PHP application?
- What are the implications of using while loops to iterate through dynamic columns in a MySQL table for data retrieval and processing in PHP?
- What are some best practices for implementing random time intervals in PHP for displaying or not displaying content?