What are the best practices for handling database queries and data retrieval in PHP scripts to avoid offset errors?

Offset errors in database queries often occur when trying to access a non-existent index in the result set. To avoid this issue, it is recommended to check if the index exists before accessing it in the retrieved data. One way to handle this is by using the isset() function to verify the existence of the index before attempting to access it.

// Example of handling database queries and data retrieval to avoid offset errors
$query = "SELECT * FROM users";
$result = mysqli_query($connection, $query);

if ($result) {
    while ($row = mysqli_fetch_assoc($result)) {
        if (isset($row['username'])) {
            echo $row['username'] . "<br>";
        } else {
            echo "Username not found<br>";
        }
    }
} else {
    echo "Error: " . mysqli_error($connection);
}