What are some best practices for importing multiple CSV files into different MySQL DB tables using PHP?
When importing multiple CSV files into different MySQL DB tables using PHP, it is important to establish a systematic approach to handle each file individually and map its data to the correct table columns. One way to achieve this is by creating a function that reads each CSV file, parses its data, and inserts it into the corresponding MySQL table. By iterating through each CSV file and table mapping, the process can be automated and streamlined.
<?php
// Function to import CSV file into MySQL table
function importCSV($csvFile, $tableName, $connection) {
$file = fopen($csvFile, 'r');
while (($data = fgetcsv($file)) !== FALSE) {
$columns = implode(',', array_map('mysqli_real_escape_string', $data));
$sql = "INSERT INTO $tableName VALUES ($columns)";
mysqli_query($connection, $sql);
}
fclose($file);
}
// Connect to MySQL database
$connection = mysqli_connect('localhost', 'username', 'password', 'database');
// List of CSV files and corresponding table names
$csvFiles = ['file1.csv', 'file2.csv', 'file3.csv'];
$tableNames = ['table1', 'table2', 'table3'];
// Import each CSV file into the corresponding MySQL table
for ($i = 0; $i < count($csvFiles); $i++) {
importCSV($csvFiles[$i], $tableNames[$i], $connection);
}
// Close MySQL connection
mysqli_close($connection);
?>