How can PHP scripts be optimized for efficiently handling the import of CSV files into specific MySQL DB tables, while ensuring data integrity and accuracy?

To optimize PHP scripts for efficiently handling the import of CSV files into specific MySQL DB tables while ensuring data integrity and accuracy, you can use PHP's built-in functions like fgetcsv() to read the CSV file line by line, validate the data before inserting it into the database, and utilize MySQL transactions for atomicity.

<?php
// Establish a connection to the MySQL database
$mysqli = new mysqli("localhost", "username", "password", "database");

// Check connection
if ($mysqli->connect_error) {
    die("Connection failed: " . $mysqli->connect_error);
}

// Start a MySQL transaction
$mysqli->begin_transaction();

// Open the CSV file for reading
if (($handle = fopen("data.csv", "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        // Validate the data before inserting into the database
        if (count($data) == 3) {
            $sql = "INSERT INTO table_name (column1, column2, column3) VALUES ('" . $mysqli->real_escape_string($data[0]) . "', '" . $mysqli->real_escape_string($data[1]) . "', '" . $mysqli->real_escape_string($data[2]) . "')";
            $mysqli->query($sql);
        }
    }
    fclose($handle);
}

// Commit the transaction
$mysqli->commit();

// Close the MySQL connection
$mysqli->close();
?>