What are the best practices for directly importing CSV data into a database using PHP?

When importing CSV data into a database using PHP, it's important to follow best practices to ensure data integrity and efficiency. One common approach is to use PHP's built-in functions like fgetcsv() to read the CSV file line by line and then insert the data into the database using prepared statements to prevent SQL injection attacks.

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

// Loop through each row in the CSV file
while (($data = fgetcsv($csvFile)) !== false) {
    // Prepare a SQL statement to insert the data into the database
    $stmt = $pdo->prepare("INSERT INTO table_name (column1, column2) VALUES (?, ?)");
    
    // Bind the values from the CSV file to the prepared statement
    $stmt->bindParam(1, $data[0]);
    $stmt->bindParam(2, $data[1]);
    
    // Execute the SQL statement
    $stmt->execute();
}

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