What are the best practices for handling and manipulating data from CSV files before inserting it into a MySQL database using PHP?

When handling and manipulating data from CSV files before inserting it into a MySQL database using PHP, it is important to properly sanitize and validate the data to prevent SQL injection attacks and ensure data integrity. Additionally, it is recommended to use PHP functions like fgetcsv() to read the CSV file and process the data before inserting it into the database.

// 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 before inserting it into the database
    $value1 = mysqli_real_escape_string($conn, $data[0]);
    $value2 = mysqli_real_escape_string($conn, $data[1]);
    
    // Insert the data into the MySQL database
    $query = "INSERT INTO table_name (column1, column2) VALUES ('$value1', '$value2')";
    mysqli_query($conn, $query);
}

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