Created
August 21, 2012 23:09
-
-
Save davidrenne/3420197 to your computer and use it in GitHub Desktop.
Import Any CSV into mySQL queries
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$file = 'C:\\data.csv'; | |
$fields = array(); | |
$sqlOutput = ''; | |
if($f = fopen($file, 'r')) | |
{ | |
$fields = fgetcsv($f); | |
fclose($f); | |
if (!empty($fields)) | |
{ | |
$sqlOutput .= "DROP TABLE IF EXISTS `import_tmp`;\n\n"; | |
$sqlOutput .= "CREATE TABLE `import_tmp` ("; | |
$sqlOutput .= '`'.implode("` mediumtext NOT NULL,\n`",$fields).'` mediumtext NOT NULL'."\n"; | |
$sqlOutput .= ") ENGINE=InnoDB DEFAULT CHARSET=utf8;\n\n"; | |
$sqlOutput .= "ALTER TABLE `import_tmp` ADD `id` INT( 11 ) NOT NULL AUTO_INCREMENT PRIMARY KEY FIRST;\n\n"; | |
$sqlOutput .= "LOAD DATA LOCAL INFILE '$file' INTO TABLE import_tmp FIELDS TERMINATED BY ',' ENCLOSED BY '\'' LINES TERMINATED BY '\\n' (`".implode("`,`",$fields)."`);\n\n"; | |
$sqlOutput .= "DELETE FROM `import_tmp` WHERE `id` = 1;\n\n"; | |
} | |
echo $sqlOutput; | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment