How can PHP beginners effectively manage and display data from a MySQL database in HTML tables?
To effectively manage and display data from a MySQL database in HTML tables, PHP beginners can use the mysqli extension to connect to the database, retrieve the data using SQL queries, and then loop through the results to display them in an HTML table format.
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "database";
// Create connection
$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);
}
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
echo "<table border='1'>";
echo "<tr><th>ID</th><th>Name</th><th>Email</th></tr>";
if ($result->num_rows > 0) {
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["id"]."</td><td>".$row["name"]."</td><td>".$row["email"]."</td></tr>";
}
} else {
echo "0 results";
}
echo "</table>";
$conn->close();
?>