views:

117

answers:

3

I am new to MySQL and PHP(as you can probably tell) and I was wondering if anybody knew an easy way to import a CSV file into a MySQL table.

"There are any number of ways to input csv into mysql depending in what kind of access you have, if you can use the mysql client directly there is a command to load delimited data, something like that could basically be entered directly in cron and keep itself up to date. Otherwise there are various php scripts to do that sort of thing."

That is something a friend told me to do, is that the easiest/best way to do it? If it is would someone mind explaining it to me?

Thank you

+1  A: 

Use the "load data infile" command. By deafulat it will treat incoming files as csv, although you can define a custom file type to import. Documentation for load data infile is here:

http://dev.mysql.com/doc/refman/5.0/en/load-data.html

FTA, in its simplest form the command looks just like this:

LOAD DATA INFILE 'data.txt' INTO TABLE db2.my_table;

That assumes the columns in the data file and in your text file line up. The rest of the documentation explains how to get non-lined up fields imported, and also how to deal with windows vs unix style line terminations.

Zak
Is it possible to put a link inplace of 'data.txt' in your above example?
Shoaulin
no, you need to download your datafile first. Use wget or curl if you are on a linux system.
Zak
With php you could also upload the file, and then use the move_uploaded_file() to place the file where you want it.
acrosman
A: 

If you're getting to MySQL and PHP a nice way I started was with XAMPP.

XAMPP is an easy to install Apache distribution containing MySQL, PHP and Perl. XAMPP is really very easy to install and to use - just download, extract and start.

The package includes phpMyAdmin which makes it really easy to upload CSVs and manage your MySQL database.

Mrgreen
Unfortunately, I am using a hosting service and I doubt they would allow me to install it but I will try it anyway :)
Shoaulin
phpMyAdmin can be installed anywhere - http://phpmyadmin.net
Till
+1  A: 

here's the step-by-step to extend Mrgreen's answer :

  1. install phpmyadmin
  2. choose your database
  3. choose your table
  4. 'Import'
  5. select your CSV file
  6. set 'Format of imported file' to CSV
andyk