Skip to content

Instantly share code, notes, and snippets.

@mmohiudd
Created September 17, 2012 16:18
Show Gist options
  • Save mmohiudd/3738271 to your computer and use it in GitHub Desktop.
Save mmohiudd/3738271 to your computer and use it in GitHub Desktop.
MySQL table generator from CSV file
<?php
// GENERATE TABLE FROM FIRST LINE OF CSV FILE
$inputFile = 'csv/sample.csv'; // path to CSV file
$tableName = 'csv'; // table name
$fh = fopen($inputFile, 'r');
$contents = fread($fh, 5120); // 5KB
fclose($fh);
$fileLines = explode("\n", $contents);
$fieldList = explode(',', $fileLines[0]);
echo "\n\n";
echo 'CREATE TABLE IF NOT EXISTS `'.$tableName.'` ('."\n";
for($i = 0; $i < count($fieldList); $i++)
{
if(strlen($fieldList[$i]) == 0)
$typeInfo = 'varchar(100)';
if(preg_match('/[0-9]/', $fieldList[$i]))
$typeInfo = 'int(11)';
if(preg_match('/[\.]/', $fieldList[$i]))
$typeInfo = 'float';
if(preg_match('/[a-z\\\']/i', $fieldList[$i]))
$typeInfo = 'varchar(100)';
echo "\t".'`'.trim($fieldList[$i]).'` '.$typeInfo.' NOT NULL, -- '.gettype($fieldList[$i]).' '.$fieldList[$i]."\n";
}
echo ' PRIMARY KEY (' . $fieldList[0] . ')'."\n";
echo ') ENGINE=MyISAM DEFAULT CHARSET=utf8 COLLATE=utf8_unicode_ci;';
echo "\n\n";
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment