six7zero9
six7zero9

Reputation: 323

php: importing multiple csv files into mysql table

<?php

error_reporting(E_ALL);
ini_set('memory_limit', '512M');
ini_set('display_errors', 'ON');

$host = "127.0.0.1"; // Host name
$username = "root"; // Mysql username
$password = ""; // Mysql password
$db_name = "test2"; // Database name
$tbl_name = "tcg_unique";

$con = mysql_connect("$host", "$username", "$password")or die("cannot connect");
$db_con = mysql_select_db($db_name) or die("cannot select DB");
$charset = mysql_set_charset('utf8',$con);

$dir_iterator = new RecursiveDirectoryIterator("/Users/jacksons/Dropbox/MTG/SQL staging");
$iterator = new RecursiveIteratorIterator($dir_iterator, RecursiveIteratorIterator::SELF_FIRST);

foreach ($iterator as $file) {
echo $file, "\n";
if(strpos($file, '.csv') !== false){
mysql_query("LOAD DATA LOCAL INFILE '$file' INTO TABLE $tbl_name") or die (mysql_error());
}
else{
    print "else";
}
}

I am tying to load multiple csv files from a directory. I am getting all the file path's to print out, but i am not able to get the data to load into the tables. I tried one in mysql and it imported with no problem (all the column names matched). Any help would be greatly appreciated.

csv looks like: cardname vendor condition price shipping quantity Date Brimaz, King of Oreskos Game Citadel Near Mint 18 0.5 4 5/30/14 Kiora, the Crashing Wave FTW Games Lightly Played 13.09 NA 1 5/30/14 Courser of Kruphix Chicagoland Games Near Mint 11.68 0.75 3 5/30/14

Upvotes: 1

Views: 2801

Answers (2)

Erico
Erico

Reputation: 1461

If your file is actually a csv file with fields separated by comma, you must specify the field separator.

LOAD DATA INFILE '$file' INTO TABLE $tbl_name FIELDS TERMINATED BY ','

If you don't state the field separator mysql considers the field separator as tab (\t).

In case the file is created with return carriage, monstly windows applications do that, you also need to add in the end of the statement:

LINES TERMINATED BY '\r\n'

Upvotes: 1

arielnmz
arielnmz

Reputation: 9145

If you want to import several csv files and you're doing it manually, you might also want to use a graphical tool to make the job easier. You can use Adminer for this:

  1. Access adminer from your browser.
  2. Log in with admin rights.
  3. Select your database.
  4. Click on the Import option on the left.
  5. Choose your .csv file.
  6. Press the Execute button.

Upvotes: 1

Related Questions