Tutorial: Import a CSV File Using PHP and MySQL
The following code should help beginner PHP/MySQL developers who are looking for an easy way to import a CSV or comma delimited file into a mysql database. This example adds new contacts into the contacts table from an uploaded CSV file, populating the following three fields: (contact_first, contact_last, contact_email).
Click to view files:
I've included the PHP code below that 'does all the work'. Click the 'import.php' link above to view the full code.
//get the csv file
$file = $_FILES[csv][tmp_name];
$handle = fopen($file,"r");
//loop through the csv file and insert into database
do {
if ($data[0]) {
mysql_query("INSERT INTO contacts_tmp (contact_first, contact_last, contact_email) VALUES
(
'".addslashes($data[0])."',
'".addslashes($data[1])."',
'".addslashes($data[2])."'
)
");
}
} while ($data = fgetcsv($handle,1000,",","'"));
//
Categories
· Mobile (1) · Projects (53) · Tutorials (12) · PHP (12) · jQuery (5) · MySQL (4)
View by date
· View All · May 2012 · March 2012 · February 2012 · January 2012 · December 2011 · November 2011 · October 2011 · September 2011 · July 2011 · June 2011 · May 2011 · April 2011 · March 2011 · February 2011 · January 2011 · December 2010 · November 2010 · October 2010 · September 2010 · July 2010 · May 2010 · April 2010 · February 2010 · January 2010 · November 2009 · August 2009 · July 2009 · May 2009 · April 2009 · March 2009 · February 2009 · January 2009 · December 2008 · November 2008 · October 2008 · June 2008