What is the process for selecting and displaying a table from a MySQL database using PHP in a web browser?
To select and display a table from a MySQL database using PHP in a web browser, you need to establish a connection to the database, execute a query to select the data from the table, fetch the results, and then display them in a tabular format on a web page.
<?php
// Establish connection to MySQL 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);
}
// Select data from table
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Display data in a table
if ($result->num_rows > 0) {
echo "<table><tr><th>Column 1</th><th>Column 2</th></tr>";
while($row = $result->fetch_assoc()) {
echo "<tr><td>".$row["column1"]."</td><td>".$row["column2"]."</td></tr>";
}
echo "</table>";
} else {
echo "0 results";
}
$conn->close();
?>
Keywords
Related Questions
- What are some best practices for efficiently iterating through JSON data in PHP and applying conditional styling based on value types?
- Welche Best Practices sollten bei IF-Strukturen in PHP beachtet werden, um Fehler zu vermeiden?
- What potential pitfalls should be considered when using array_diff() with multiple arrays in PHP?