Skip to content
PHP Logo

What are some common mistakes to avoid when fetching and displaying database entries in PHP, especially when dealing with arrays and specific fields like IDs?

One common mistake when fetching and displaying database entries in PHP is not properly handling array indexes, especially when dealing with specific fields like IDs. To avoid errors, always check if the array key exists before trying to access it. Additionally, make sure to sanitize and validate user input to prevent SQL injection attacks.

php
// Fetching database entries and displaying them with proper error handling
$query = "SELECT * FROM table";
$result = mysqli_query($connection, $query);

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        if (isset($row['id'])) {
            echo "ID: " . $row['id'] . "<br>";
        } else {
            echo "ID not found" . "<br>";
        }
    }
} else {
    echo "Error fetching data from database";
}