What are some best practices for reading CSV files into a database table using PHP to avoid data corruption?

When reading CSV files into a database table using PHP, it is important to handle data validation and sanitization to prevent data corruption. One way to achieve this is by using prepared statements to insert data into the database, which helps to prevent SQL injection attacks. Additionally, it is recommended to check for any potential errors during the file reading process and handle them appropriately to ensure data integrity.

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=database', 'username', 'password');

// Open the CSV file for reading
$handle = fopen('data.csv', 'r');

// Loop through each row in the CSV file
while (($data = fgetcsv($handle)) !== false) {
    // Sanitize and validate data before inserting into the database
    $stmt = $pdo->prepare("INSERT INTO table (column1, column2) VALUES (?, ?)");
    $stmt->execute([$data[0], $data[1]]);
}

// Close the file handle
fclose($handle);