What are the best practices for connecting to a database and fetching data in PHP to prevent undefined offset errors?

When fetching data from a database in PHP, it is important to handle potential undefined offset errors that may occur when accessing array elements that do not exist. To prevent these errors, you can check if the array key exists before accessing it using isset() or array_key_exists() functions.

// Connect to the database
$connection = new mysqli('localhost', 'username', 'password', 'database');

// Fetch data from the database
$query = "SELECT * FROM table";
$result = $connection->query($query);

if ($result->num_rows > 0) {
    while ($row = $result->fetch_assoc()) {
        // Check if the array key exists before accessing it
        if (isset($row['column_name'])) {
            // Process the data
        }
    }
}

// Close the database connection
$connection->close();