Is there a way to import multiple csv files at the same time into a MySQL database? Some sort of batch import?
I\'m on Mac OSX running a MAMP server.
I have
i had the same task to do with a lot of CSV files and create one table by CSV, so here is my script that i use in local under XAMP.
';
$mysqli = new mysqli(
"localhost",
"root",
"",
"mydatabase",
3306
);
if (mysqli_connect_errno()) {
printf("Connect failed: %s\n", mysqli_connect_error());
exit();
}
$files = glob('C:\\xampp\\mysql\\data\\mev2\\*.csv');
foreach($files as $file){
//clean names if needed
$filename = explode('\\',$file);
$filename2clean = str_replace('.csv','', $filename[5]);//because my file is under 5 folders on my PC
$n = strtolower(str_replace('fileprefix_','', filename2clean));
echo '
Create table '.$n.'
';
$sql = "CREATE TABLE IF NOT EXISTS `mydatabase`.`".$n."` (`email` varchar(60), `lastname` varchar(60), `firstname` varchar(60), `country` varchar(19)) DEFAULT CHARACTER SET utf8 COLLATE utf8_general_ci;";
if (!($stmt = $mysqli->query($sql))) {
echo "\nQuery execute failed: ERRNO: (" . $mysqli->errno . ") " . $mysqli->error;
};
echo '
Import data from '.$n.'
';
$sql = "LOAD DATA INFILE '".basename($file)."' INTO TABLE `mydatabase`.`".$n."`
FIELDS TERMINATED BY ';'
LINES TERMINATED BY '\r'
IGNORE 1 LINES";
if (!($stmt = $mysqli->query($sql))) {
echo "\nQuery execute failed: ERRNO: (" . $mysqli->errno . ") " . $mysqli->error;
};
}
echo '### Import finished !
';