Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 0 additions & 6 deletions README

This file was deleted.

26 changes: 26 additions & 0 deletions README.MD
Original file line number Diff line number Diff line change
@@ -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
17 changes: 15 additions & 2 deletions php-csv2mysql.php
Original file line number Diff line number Diff line change
Expand Up @@ -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');

Expand Down Expand Up @@ -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;
Expand Down