PHP Script to transfer csv file to MySql

Posted on 2012-04-09
Medium Priority
Last Modified: 2012-04-24
Hi experts,

I need a script that will transfer a csv file to a table in my db.  Sounds pretty straightforward but I'm going to throw a slight kink in it...

The csv file and the db table do not match.  I'm going from mssql to mysql and I've dumped all the data from each table in to a csv file.  My company is converting our asp site to a php site and the information we handle is Law Enforcement Sensitive so they have to have someone with the proper security clearance to do it.  When the new site db was made, a lot of features are different or upgraded and no longer needed.  So in my csv file I have for instance:

First_Name, Last_Name, email, password, date_joined, date_last_posted

and in the new db I would have the fields:

name, email, password, something else, ...etc

The way I was thinking in my head was taking each csv line and explode() the comma's and then use the array keys to enter the data?  I'm sure there is probably an easier way.  I need all the help I can get.

There are around 51,000 users if that makes a difference but the largest csv file is well over 250k records.
Question by:deputycheek
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
LVL 32

Expert Comment

ID: 37825572
Explode is not going to be a good solution. If there is a comma or something else random in a field, it will kill the import.

You're better off looping through the files to get them structured correctly using: http://php.net/manual/en/function.fgetcsv.php.

Read the file, and write a new one that is properly formatted for the new DB.

THEN... use mysqlimport to import the CSV file. It will be faster and better.


Depending on your structure, you'll want to use these switches:

*in case you need to map the columns.

*If your fields are enclosed with quotes.

*If some fields are enclosed in quotes and others aren't.

*If you have any escaped fields (usually a "no"... but included for completeness.

*appears that this will be a comma in your case, whcih is the default. But if you have a tab or ;, use this.

*usually CRLF in Windows or just a LF in Linux / Mac.

Author Comment

ID: 37825614
What I do now is import the csv file straight in to mysql and I wrote a function that takes what I need from one table and places it in to the other.  The only problem with that is some of the files timeout and have to be broken in to pieces etc...

I was just hoping there was a way to "cut out the middle man" so to speak because the new user table is so much different.

I didn't know if I could take like the 1st, 8th, and 11th value from each line on the csv and insert straight in to the db...which would make my life soooo much easier.  Pretty much picking and choosing.

Another reason is some of the old tables were combined in to one on the new site so It'd be nice to read line by line of two seperate csv files and take what I need from them.

Here's what I have now for CI in case someone wants to use the long way:

 public function users_to_user($start,$limit)
		$users = $this->migrate_model->getUsers($start,$limit); // gets from users table (old field names)
		foreach ($users as $u) {

		    // recid -> id
		    // UserId -> username
		    // Password -> password
		    $u->Password = md5($u->Password);
		    // UserType -> user_type_id
		    // in the new sys, admin is 99 old is 3
		    if ($u->UserType == 3) {
			$u->UserType = 99;

Open in new window

and of course I get the table name from the model.  

but there HAS to be a way to do it the other way.

Accepted Solution

rinfo earned 2000 total points
ID: 37826834
$path_length = strrpos(__FILE__,DIRECTORY_SEPARATOR);
       $path  = substr(__FILE__, 0, $path_length) .DIRECTORY_SEPARATOR;
       $csv_with_path = "{$path}{$temp_csv_file}";

       $q="LOAD DATA LOCAL INFILE  '$temp_csv_file' INTO TABLE yourtablename
                                FIELDS TERMINATED BY \"\,\"
                                LINES TERMINATED BY \"\n\"
                                (mysql table fieldlist separted by comma and unquoted )";

       mysql_query($q) or die(mysql_error());

if csv file contains header as field name  you have to add IGNORE 1 LINES after the closing
bracket of the fieldlist.
This is a tested code and i have used it successfully.
Survive A High-Traffic Event with Percona

Your application or website rely on your database to deliver information about products and services to your customers. You can’t afford to have your database lose performance, lose availability or become unresponsive – even for just a few minutes.

LVL 111

Expert Comment

by:Ray Paseur
ID: 37826992
You might be able to get something to work using phpMyAdmin.  Failing that, I would write a thing that us computer science geeks call a polymorphic adapter.  It has one side that is the output side, and in that side it creates a CSV file that is exactly what you need for something like LOAD DATA INFILE.  It has one or more sides that are the input sides, and these are the polymorphs.  Each of these reads a file with some kind of data that is sort of like what you need (the old stuff).  They map the  data in such a way that it's exactly what the output side needs to write.

If you want to post the exact field names, and a description of the mappings, including the CREATE TABLE statements for all of the tables involved, we may be able to show you how an adapter will work.
LVL 15

Expert Comment

ID: 37827093
hi , simply use LOAD DATA INFILE


$file ='xyz.csv';
$query = "LOAD DATA LOCAL INFILE '".$file."' INTO TABLE tablename FIELDS TERMINATED BY ' \\t ' LINES TERMINATED BY '\n' IGNORE 0 LINES (table_filed1, to_table_filed2,table_filed3);";
LVL 16

Expert Comment

by:theo kouwenhoven
ID: 37827117
If the CSV is created the right way, you can insert the records from PHP per line

$file = fopen($xCsvFile,"r");
      $rec = fgets($file);
      while(! feof($file))
            $query  = "INSERT INTO Track (Fld01, Fld02, Fld03, Fld04, Fld05) VALUES ($rec)" ;
            $result = mysql_query($query) or die(mysql_error());
            $rec = fgets($file);

If the $rec contains more fields then you need, use an worktable first, or add temp dummy fields to the target file,
but adding a CSV record to a table is no problem :-)

Featured Post

Concerto's Cloud Advisory Services

Want to avoid the missteps to gaining all the benefits of the cloud? Learn more about the different assessment options from our Cloud Advisory team.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

A while back, I ran into a situation where I was trying to use the calculated columns feature in SharePoint 2013 to do some simple math using values in two lists. Between certain data types not being accessible, and also with trying to make a one to…
There are times when I have encountered the need to decompress a response from a PHP request. This is how it's done, but you must have control of the request and you can set the Accept-Encoding header.
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
In this video, Percona Solution Engineer Rick Golba discuss how (and why) you implement high availability in a database environment. To discuss how Percona Consulting can help with your design and architecture needs for your database and infrastr…
Suggested Courses

649 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question