Home
 

Customer Support

Search for keywords:

Browse by category:

How do I import delimited data into MySQL?

If you have data that you need to bring into your MySQL database, there are a few ways to do it. Exporting data out of mysql is another topic, described here.

1. Using the LOAD DATA INFILE SQL statement

For security reasons, no one has the mysql FILE priv, which means you cannot "LOAD DATA INFILE". You can, however, use a "LOAD DATA LOCAL INFILE" statement as long as you have a mysql prompt on our system and have uploaded the data file to your account here first.

The "LOAD DATA LOCAL INFILE" statement will only work from a MySQL prompt on our local system. It will not work from any web-based tool such as phpMyAdmin, and will never pull a file in directly off your own computer.

To import a file this way, first upload your data file to your home directory on our system with FTP or SCP. Then get a shell prompt on our system, and then a MySQL Monitor prompt so that you can issue the SQL that will import your file.

For example, suppose you have a data file named importfile.csv that contains 3 comma separated columns of data on each line. You want to import this textfile into your MySQL table named test_table, which has 3 columns that are named field1, field2 and field3.

To import the datafile, first upload it to your home directory, so that the file is now located at /importfile.csv on our local system. Then you type the following SQL at the mysql prompt:
LOAD DATA LOCAL INFILE '/importfile.csv'
INTO TABLE test_table
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'
(field1, filed2, field3);
The above SQL statement tells the MySQL server to find your INFILE on the LOCAL filesystem, to read each line of the file as a separate row, to treat any comma character as a column delimiter, and to put it into your MySQL test_table as columns field1, field2, and field3 respectively. Many of the above SQL clauses are optional and you should read the MySQL documentation on the proper use of this statement.

2. Using a script to parse and import the file

You can also write a script in any programming language that can connect to MySQL (such as PHP) to open your data file, break it up into an array of lines that each represent a row of data, split each line up by the delimiter character (such as a comma ',', tab '\t', semicolon ';', space ' ', etc.), and then perform invididual MySQL INSERT queries (one INSERT for each line) to insert all your data from the file into the appropriate table fields.

Such scripts are not difficult to write in less than 15 lines and can import data from text files just as effectively as a LOAD DATA LOCAL INFILE command. A working example script written in PHP appears below in the Annotations.

3. Importing a mysqldump

If your data file actually comes from another MySQL database, and not from Excel or any other source, then the most direct way to export and import your data would be to dump out your table or entire MySQL database on the original database server using the mysqldump command, FTP the resulting dump file to your account here, and then import the dump file at a shell prompt.

For instructions on creating the dumpfile using the mysqldump command, see this FAQ. For instructions on how to import a dump made with mysqldump, see this FAQ.

User-Contributed Notes

add a note
14-Jun-2002 01:44
If you need to take a csv or other delimited data file and import it
INTO MySQL, here is a php script that can do it for you:

<?
   # first get a mysql connection as per the FAQ

  $fcontents = file ('./spreadsheet.xls'); 
  # expects the csv file to be in the same dir as this script

  for($i=0; $i<sizeof($fcontents); $i++) { 
      $line = trim($fcontents[$i]); 
      $arr = explode("\t", $line); 
      #if your data is comma separated
      # instead of tab separated, 
      # change the '\t' above to ',' 
     
      $sql = "insert into TABLENAME values ('". 
                  implode("','", $arr) ."')"; 
      mysql_query($sql);
      echo $sql ."<br>\n";
      if(mysql_error()) {
         echo mysql_error() ."<br>\n";
      } 
}
?>

Upload a spreadsheet file into the same directory as this script. Then
you edit this script to put in the correct table name instead of 
"TABLENAME".

So long as your xls file is tab delimited and has 1 row per line with
all columns in the same order that your mysql database columns are, then
this script will pull all the data out of your XLS file and insert it
all into mysql. Don't forget to connect to mysql in the script before
anything else with a mysql_connect() and mysql_select_db() as shown here
http://www.modwest.com/help/kb6-60.html

04-Jan-2004 16:38
Here is an example of creating a data file and then importing it with
LOAD DATA syntax.

mulder@modwest:/$ echo 'a b c d' > testfile
mulder@modwest:/$ mysql

Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 3979754 to server version: 4.0.15-Max-log

mysql> CREATE TABLE `test` (
    -> `fe` VARCHAR( 2 ),
    -> `fi` VARCHAR( 2 ),
    -> `fo` VARCHAR( 2 ),
    -> `fum` VARCHAR( 2 )
    -> );
Query OK, 0 rows affected (0.00 sec)

mysql> load data LOCAL infile '/testfile' into table test 
fields terminated by ' ' lines terminated by '\n';  
Query OK, 1 row affected (0.02 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql> select * from test;
+------+------+------+------+
| fe   | fi   | fo   | fum  |
+------+------+------+------+
| a    | b    | c    | d    |
+------+------+------+------+
1 row in set (0.00 sec)

mysql> load data LOCAL infile '/testfile' into table test 
fields terminated by ' ' lines terminated by '\n' (fum, fo, fi, fe); 
 
Query OK, 1 row affected (0.02 sec)
Records: 1  Deleted: 0  Skipped: 0  Warnings: 0

mysql> select * from test;
+------+------+------+------+
| fe   | fi   | fo   | fum  |
+------+------+------+------+
| a    | b    | c    | d    |
| d    | c    | b    | a    |
+------+------+------+------+
2 rows in set (0.00 sec)

mysql> exit


If you don't have your .my.cnf preference file set as per:
http://www.modwest.com/help/kb.phtml?cat=6&qid=242
then you won't get into the Monitor with just a 'mysql'.

You'll need to provide all the required parameters as per:
http://www.modwest.com/help/kb6-60.html

07-May-2005 22:01
From the example above:

<?
   # first get a mysql connection as per the FAQ

  $fcontents = file ('./spreadsheet.xls'); 
  # expects the csv file to be in the same dir as this script

  for($i=0; $i<sizeof($fcontents); $i++) { 
      $line = trim($fcontents[$i]); 
      $arr = explode("\t", $line); 
      #if your data is comma separated
      # instead of tab separated, 
      # change the '\t' above to ',' 
     
      $sql = "insert into TABLENAME values ('". 
                  implode("','", $arr) ."')"; 
      mysql_query($sql);
      echo $sql ."<br>\n";
      if(mysql_error()) {
         echo mysql_error() ."<br>\n";
      } 
}
?>

Many feeds have blank fields. To maintain the correct field count in
each row for the fields in the database, change this line:     $line =
trim($fcontents[$i]);   TO      $line = trim($fcontents[$i], '\t');  for
tab delimited files or  ',' for comma delimited, etc.

anonymous -at- example.com
17-May-2005 11:39
The code was not doing what I had in mind, so I  modified the code
untill I was finally able to accomplish what I needed to do.  

the test.csv files contains data llike:
"name","userid"
"john","jon"

there were only two lines that I had to modify from the original code:

$arr = explode("\"", $line);
and
$sql = "insert into test values (". implode("'", $arr) .")";

Full code:
<?php
connection = mysql_connect("localhost", "test", "test") or die ("Unable
to connect to server");
      3 $db = mysql_select_db("test", $connection) or die ("Unable to
select database");
      4
      5  #mysql connection as per the FAQ
      6
      7    $fcontents = file ('./test.csv');
      8      # expects the csv file to be in the same dir as this script
      9
     10        for($i=0; $i<sizeof($fcontents); $i++) {
     11        $line = trim($fcontents[$i]);
     12        echo "$line<BR>";
     13        $arr = explode("\"", $line);
     14        echo "$arr";
     15        #if your data is comma separated
     16        # instead of tab separated,
     17        # change the '\t' above to ','
     18
     19        $sql = "insert into test values (". implode("'", $arr)
.")";
     20        #$sql = "insert into test values ('". $arr ."')";
     21        mysql_query($sql);
     22        echo $sql ."<br>\n";
     23        if(mysql_error()) {
     24        echo mysql_error() ."<br>\n";
     25        }
     26    }
     27  ?>

I'm sure there is a better way to do the above, but for now this will
do.

anonymous -at- example.com
17-Oct-2005 20:10
Have a look at http://www.php.net/fgetcsv for an easier way to import
CSV files

webmaster -at- php.com
28-Oct-2005 14:39
How to do this from a php script:
http://www.webmasterworld.com/forum88/10592.htm

dan2340 -at- optusnet.com.au
17-Feb-2006 23:11
Hi
I have PHP 5 and MYSQL set up on localhost Win XP Home.
Do what you want with this in PHP it imports a csv file. Cheers

LOAD DATA INFILE "./ImportData.csv"
     INTO TABLE table1
     FIELDS TERMINATED BY ","
     OPTIONALLY ENCLOSED BY """"
     LINES TERMINATED BY "\r\n";

OPTIONALLY ENCLOSED is optional.

anonymous -at- example.com
02-Nov-2006 11:02
The fgetcsv PHP function was able to save me in this case. Here's a code
snippet:

$handle = fopen ('./file.csv', 'r');
		while (($data = fgetcsv($handle, 1000, ',', '"')) !== FALSE)
		{
			$query = "INSERT INTO services VALUES ('". implode("','", $data)
."')";
 			$query = @mysql_query($query);
		}

This certainly got me out of a fix

samidba -at- hotmail.com
27-Nov-2006 12:13
To load data from Delimited textfiles to MySQL you can try Data Loader
2.0 tool. I find this tool quite good. website http://www.dbload.com

ejboy
14-Feb-2007 10:19
See http://snippets.dzone.com/posts/show/3508 for example on how to load
CSV data into a database with open source Scriptella ETL tool.

james -at- symphony-os.co.uk
16-Sep-2008 15:08
In response to anonymous -at- example.com  02-Nov-2006 11:02 extremely
helpful post, I have an amendment to his  query. Problems arise if an
apostrophe is contained in any of the csv  fields, say a name like
O'Rourke. Normally you would use the handy  mysql_real_escape_string
function, but as this is an array it does not  apply. So, instead of
enclosing the fields in the Values bit of the  query with an apostrophe,
try:

$query = "INSERT INTO Exhibitors VALUES (\"". implode("\",\"", $data) 
."\")";   

Hope this helps someone out.    

jtricari -at- rutgers.edu
04-Nov-2008 00:33
Don't forget to add slashes before making your SQL query. Simply add...

 array_map('addslashes', $arr);


06-May-2009 12:41
If your database will not accept '' as a blank, and you need a NULL
instead, add this code before mysql_querty($sql);

 $sql = str_replace("' '", mysql_escape_string("NULL"), $sql);







<?php

 # first get a mysql connection as per the FAQ

 include "database.php";

 $fcontents = file ('./operators.csv');

 # expects the csv file to be in the same dir as this script

 for($i=0; $i<sizeof($fcontents); $i++) {

         $line = trim($fcontents[$i],',');   //   '\t' for tab delimeted
        $arr = explode(',', $line);         //   '\t' for tab delimeted

        #  if your data is comma separated
        #  instead of tab separated
        #  change the '\t' above to ','

        $sql = "insert into operators values ('". implode("','", $arr)
."')";

        $sql = str_replace("''", mysql_escape_string("NULL"), $sql);

        $sql = str_replace("' '", mysql_escape_string("NULL"), $sql);

        mysql_query($sql); echo $sql ."<br>\n";

        if(mysql_error()) {
                echo mysql_error() ."<br><b><font color=red>\n</b>";
        }

 } ?>



08-May-2009 14:30
Be mindful of the text encoding.  I was doing this kind of project and
entering thousands of blank rows, it took me a while to realize the text
encoding of the source document was UTF-16.

I created a second array after each line of the document to hold the
converted contents of the original.  Then did the INSERT INTO with the
contents of the converted arrary.

add a note

Related Questions:


How do I import a MySQL dumpfile into my database?

How do I connect to my MySQL database?

How do I change my MySQL password?

How can I export data in CSV or tab delimited format?

Why do i get a query syntax error 1064 from MySQL when the syntax seems correct?

How do I export and move my database tables between servers or copy databases?

How do I create a .my.cnf MySQL preference file?

I can't connect to local MySQL server through socket 'mysql.sock'

How do I change MySQL timezone?

What is my database server name?

What is my MySQL Username or Database Name?

MySQL says I have too many connections.

How do I check how much disk space my database is using?

A MySQL MYI table has errors in it.

Can I connect to MySQL remotely?

Can I connect to my MySQL database from my own computer?

I can't get phpMyAdmin to work.

phpMyAdmin gives SQL syntax error when I try to create table.

How can I use odbc_connect() in my PHP scripts to connect to MySQL?

What kind of database server do you offer?

How do I import a MySQL dumpfile into my database via phpMyAdmin?

How many databases do I get?

What am I allowed to do with my MySQL database?

Will we be able to do our own MySQL admin?

How do I export a MySQL dumpfile via phpMyAdmin?

Do you offer MySQL 5?

How do I create a MYSQL dumpfile?

How do I update my web application to connect to a different database server?

How do I create a MYSQL database for my webhosting account?

Browse Categories:

Getting Started, FTP, Telnet/SSH, Moving Domains, E-mail, Traffic Reports, Mailing Lists, Apache, PHP, CGI, Other Server-Side Scripting, MySQL Database, Imaging Libraries, Other Software, Billing & Terms, Control Panel, E-commerce, Pre-Sales


Modwest PHP Hosting      Copyright 2000-2009 by Modwest, Inc.      About    |    Blog    |    Community    |    Design    |    Jobs    |    Contact