What are some common mistakes made by beginners when trying to display database entries in a table using PHP?
One common mistake made by beginners when trying to display database entries in a table using PHP is not properly fetching the data from the database and displaying it in the table structure. To solve this, you need to use a loop to iterate over the fetched data and output it within the table rows and cells.
<?php
// Connect to the 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);
}
// Fetch data from the database
$sql = "SELECT * FROM table_name";
$result = $conn->query($sql);
// Display data in a table
echo "<table>";
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>";
// Close connection
$conn->close();
?>
Keywords
Related Questions
- What are some potential pitfalls when trying to extract large amounts of data from a MySQL database using PHP?
- What are the advantages and disadvantages of using subdomains versus directories for user-specific pages in PHP?
- How can prepared statements be used to securely insert form data into a MySQL database in PHP?