Skip to content

Instantly share code, notes, and snippets.

@davidrenne
Created August 21, 2012 23:09
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save davidrenne/3420197 to your computer and use it in GitHub Desktop.
Save davidrenne/3420197 to your computer and use it in GitHub Desktop.
Import Any CSV into mySQL queries
<?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