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 methods for implementing a page loading status indicator using JavaScript and PHP?
- How can PHP developers effectively incorporate HTML codes into their PHP scripts while maintaining code readability and efficiency?
- What potential problems can arise when integrating the code snippet provided into the existing online.php file?