CSV file uploading with thousands of records

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
pbs
Forum Contributor
Posts: 230
Joined: Fri Nov 07, 2008 5:31 am
Location: Nashik, India
Contact:

CSV file uploading with thousands of records

Post by pbs »

Hi All,

Is there any script by which I can upload CSV file with thousands of records in to mysql database.

Thanks
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: CSV file uploading with thousands of records

Post by Mark Baker »

phpmyadmin?
pbs
Forum Contributor
Posts: 230
Joined: Fri Nov 07, 2008 5:31 am
Location: Nashik, India
Contact:

Re: CSV file uploading with thousands of records

Post by pbs »

Thanks for you reply, but I want PHP code to do that.
Mark Baker
Forum Regular
Posts: 710
Joined: Thu Oct 30, 2008 6:24 pm

Re: CSV file uploading with thousands of records

Post by Mark Baker »

pbs wrote:Thanks for you reply, but I want PHP code to do that.
phpmyadmin?
User avatar
Darhazer
DevNet Resident
Posts: 1011
Joined: Thu May 14, 2009 3:00 pm
Location: HellCity, Bulgaria

Re: CSV file uploading with thousands of records

Post by Darhazer »

offtopic:
you can use load data infile for that

As for the php script, without knowing the table name and column names... does the CSV file include column names as first line? Should be there any mapping?
woahtuff
Forum Newbie
Posts: 4
Joined: Wed Aug 26, 2009 10:36 pm

Re: CSV file uploading with thousands of records

Post by woahtuff »

This is the script I use to upload a .csv into mysql. I haven't used it in a while, but I believe the column names in the .csv need to match the fields in the table. Replace 'username', 'password', 'your_db', 'your_file.csv' and 'your_table' with your values. I've uploaded about 2500 records into my db at once this way.

$con = mysql_connect("localhost","username","password");
if (!$con)
{
die('Could not connect: ' . mysql_error());
}

mysql_select_db("your_db", $con);

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

for($i=0; $i<sizeof($fcontents); $i++) {
$line = trim($fcontents[$i], ',');
$arr = explode(',', $line);

$sql = 'INSERT INTO your_table VALUES ("' . implode('","', $arr) . '")';
mysql_query($sql);
echo $sql .'<br>';
if(mysql_error()) {
echo mysql_error() .'<br>';
}
}
mysql_close($con);
Post Reply