What are some best practices for handling MySQL errors in PHP when importing CSV files?

When importing CSV files into MySQL using PHP, it is important to handle any potential errors that may occur during the process. One common error is a MySQL syntax error, which can occur if the CSV data does not match the table structure. To handle MySQL errors, you can use try-catch blocks in PHP to catch any exceptions thrown by the MySQL query and handle them accordingly.

try {
    // Your code to import CSV file into MySQL
    $query = "LOAD DATA INFILE 'file.csv' INTO TABLE table_name FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' IGNORE 1 LINES";
    $result = mysqli_query($connection, $query);

    if (!$result) {
        throw new Exception(mysqli_error($connection));
    }

    // Other code to handle successful import
} catch (Exception $e) {
    echo "Error importing CSV file: " . $e->getMessage();
}