How can you display data from a database in an HTML table using PHP?
To display data from a database in an HTML table using PHP, you need to first establish a connection to the database, query the data you want to display, and then loop through the results to output them in a table format within your HTML code.
<?php
// Establish a connection to the database
$host = 'localhost';
$user = 'username';
$password = 'password';
$database = 'database_name';
$connection = mysqli_connect($host, $user, $password, $database);
// Query the database for the data you want to display
$query = "SELECT * FROM table_name";
$result = mysqli_query($connection, $query);
// Output the data in an HTML table
echo "<table>";
while ($row = mysqli_fetch_assoc($result)) {
echo "<tr>";
foreach ($row as $value) {
echo "<td>" . $value . "</td>";
}
echo "</tr>";
}
echo "</table>";
// Close the database connection
mysqli_close($connection);
?>
Keywords
Related Questions
- What potential pitfalls should be considered when using the mail() function in PHP to send emails with sensitive customer data?
- What is the purpose of the PHP code provided in the forum thread and what issue is the user facing with array manipulation and output generation?
- What is the significance of placing session_start() at the beginning of a PHP script, and what potential issues can arise if it is not done so?