What are the best practices for handling CSV data in PHP and parsing it for database insertion?

Handling CSV data in PHP and parsing it for database insertion involves reading the CSV file, parsing each row into an array, and then inserting the data into the database table. It is important to properly handle errors, sanitize input data, and use prepared statements to prevent SQL injection attacks.

<?php
// Open the CSV file for reading
$csvFile = fopen('data.csv', 'r');

// Loop through each row in the CSV file
while (($data = fgetcsv($csvFile)) !== false) {
    // Sanitize and validate the data
    $column1 = filter_var($data[0], FILTER_SANITIZE_STRING);
    $column2 = filter_var($data[1], FILTER_SANITIZE_STRING);
    
    // Prepare the SQL statement using prepared statements
    $stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
    
    // Bind parameters and execute the statement
    $stmt->execute([$column1, $column2]);
}

// Close the CSV file
fclose($csvFile);
?>