How can a PHP developer optimize the loop logic to prevent fatal errors when inserting new entries into a database?

When inserting new entries into a database, a PHP developer can optimize the loop logic by checking for errors and handling them gracefully. One common issue that can lead to fatal errors is trying to insert duplicate entries into a database with a unique constraint. To prevent this, the developer can use a try-catch block to catch any exceptions thrown by the database query and handle them appropriately.

try {
    // Loop through new entries to insert into the database
    foreach ($newEntries as $entry) {
        // Perform database insert query
        $query = "INSERT INTO table_name (column1, column2) VALUES ('$entry['value1']', '$entry['value2']')";
        $result = $pdo->query($query);
        
        // Check for errors and handle them gracefully
        if (!$result) {
            throw new Exception("Error inserting entry: " . $pdo->errorInfo()[2]);
        }
    }
} catch (Exception $e) {
    // Handle the error, log it, and continue processing other entries
    echo "Error: " . $e->getMessage();
}