How can PHP be used to output MySQL query results in a table on a website?
To output MySQL query results in a table on a website using PHP, you can fetch the results from the database using MySQL queries and then loop through the results to display them in an HTML table format. You can use PHP's MySQLi or PDO extension to connect to the database, execute the query, and fetch the results. Then, you can use HTML markup within PHP to display the results in a table on the website.
<?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);
}
// Execute MySQL query
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Output results in a table
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 "<tr><td colspan='3'>No results found</td></tr>";
}
echo "</table>";
// Close database connection
$conn->close();
?>
Keywords
Related Questions
- What are the best practices for handling and merging two tables in PHP before inserting them into a SQL database?
- What are best practices for efficiently filling a switch case function with data retrieved from a database in PHP?
- How can Google Analytics be integrated with PHP to track Adwords campaigns and conversions more effectively?