How can PHP beginners streamline the process of outputting data from a MySQL database into HTML tables?
To streamline the process of outputting data from a MySQL database into HTML tables, PHP beginners can use a combination of SQL queries to retrieve data from the database and PHP loops to iterate over the results and generate the HTML table dynamically.
<?php
// Connect to the database
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database_name";
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
// Query to retrieve data from the database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Generate HTML table dynamically
if ($result->num_rows > 0) {
echo "<table><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>";
} else {
echo "0 results";
}
// Close the connection
$conn->close();
?>