diff --git a/README b/README deleted file mode 100644 index b0cb50f..0000000 --- a/README +++ /dev/null @@ -1,6 +0,0 @@ -Chris Armstrong -chris@chrisarmstrong.me - -Converts CSV files to .SQL files, with a CREATE TABLE and INSERT statements for each row of the CSV. -Will automatically ignore columns that contain no data, and will make all columns type VARCHAR with a size equal to the length of that column's longest value. -TO USE: php csv_to_sql.php inputfile.csv outputfile.sql database_name diff --git a/README.MD b/README.MD new file mode 100644 index 0000000..8936188 --- /dev/null +++ b/README.MD @@ -0,0 +1,26 @@ +#php-csv2mysql + +**Note on most conditions it is much better to simply import the CSV file using the fast import which will get you done in seconds rather than minutes or hours** + +**Reccomended sytnax with CSV import:** +**_LOAD DATA LOCAL INFILE 'file.csv' INTO TABLE table +FIELDS TERMINATED BY ',' LINES TERMINATED BY '\n' +(@col1,@dummy,@col3) set +EX1=@col1,EX2=@col3;_** + +Converts CSV files to .SQL files, with a CREATE TABLE and INSERT statements for each row of the CSV. +Will automatically ignore columns that contain no data, and will make all columns type VARCHAR with a size equal to the length of that column's longest value. + +## Instructions +1. Replace the mysql connect database and password name the applicaion. + +### To Use + +```bash +php csv_to_sql.php inputfile.csv outputfile.sql database_name +``` + +## Optional Commands + +### Disable automatically primary key to first column +--nopk diff --git a/php-csv2mysql.php b/php-csv2mysql.php index 0842be4..a992a49 100644 --- a/php-csv2mysql.php +++ b/php-csv2mysql.php @@ -3,6 +3,7 @@ $IMPORT_FILE = $argv[1]; $EXPORT_FILE = $argv[2]; $DB_NAME = $argv[3]; + $OPTION = $argv[4]; $PK_INDEX = 0; $TABLE_NAME = basename($EXPORT_FILE,'.sql'); @@ -38,10 +39,22 @@ fwrite($output,"CREATE TABLE `$DB_NAME`.`$TABLE_NAME` (\n"); for($i = 0; $i< $numCols; $i++){ if( !$unused_cols[$i] ){ - fwrite($output,'`'.$col_headings[$i]."` VARCHAR(".$cols[$i]."),\n"); + if ($i == $numCols-1&&$OPTION == "--nopk") { + fwrite($output,'`'.$col_headings[$i]."` VARCHAR(".$cols[$i].")\n"); + } + else { + fwrite($output,'`'.$col_headings[$i]."` VARCHAR(".$cols[$i]."),\n"); + + } } } - fwrite($output,"PRIMARY KEY (`$col_headings[$PK_INDEX]`)\n) DEFAULT CHARACTER SET 'utf8';\n\n"); + + // Write primary key or not + if ($OPTION != "--nopk") { + fwrite($output,"PRIMARY KEY (`$col_headings[$PK_INDEX]`)\n"); + } + // Write character set + fwrite($output, ") DEFAULT CHARACTER SET 'utf8';\n\n"); // Re-open import file $file = fopen($IMPORT_FILE,'r'); $lineNum = 1;