Reading a CSV file

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
Jeeee
Forum Newbie
Posts: 10
Joined: Sun Aug 03, 2008 11:18 am

Reading a CSV file

Post by Jeeee »

Hello Fellow coders,

I'm new to the forum and I'm in need of info. I'm trying to parse a CSV file, with header, then upload the info in my MySql DB.. Could anyone give me a hand on that.

Right now I managed to be able to read the CSV file but I'm confused on how to Import everything in MySql DB without that header.

Thank you for the help
User avatar
jaoudestudios
DevNet Resident
Posts: 1483
Joined: Wed Jun 18, 2008 8:32 am
Location: Surrey

Re: Reading a CSV file

Post by jaoudestudios »

Do you have phpmyadmin? as that is all built-in
Jeeee
Forum Newbie
Posts: 10
Joined: Sun Aug 03, 2008 11:18 am

Re: Reading a CSV file

Post by Jeeee »

Nope I'm using regular MySQL, what difference does it do if I use phpmyadmin??
User avatar
jaoudestudios
DevNet Resident
Posts: 1483
Joined: Wed Jun 18, 2008 8:32 am
Location: Surrey

Re: Reading a CSV file

Post by jaoudestudios »

phpmyadmin, is a web interface that communicates with the database. So makes it very easy to do (obviously there are limitation to what it can do, but for everyday stuff it is very good).

Import & Export can be achieved within a few seconds.

To import using a mysql dump script, select the relevant database, then use...

Code: Select all

 
mysql> use ******;
mysql> source *****.sql;
 
Alan01252
Forum Newbie
Posts: 12
Joined: Sun Aug 03, 2008 3:20 pm

Re: Reading a CSV file

Post by Alan01252 »

If you want to do this without using phpmyadmin and directly using code

testFile.csv
===============
car,blue,2004
bike,red,2006
===========

Code: Select all

 
//Read in file
$myFile = "testFile.csv";
$fh = fopen($myFile, 'r');
while (!feof($handle)) 
{ 
 $line = fgets($handle); 
 $array = explode(",", $line);
 $type = $array[0];
 $color = $array[1];
 $year = $array[2];
 
 $sql = "insert into table (type,color,year) values ($type,$color,$year)";
} 
fclose($fh);
echo $theData;
 //read in line
 
 
User avatar
omniuni
Forum Regular
Posts: 738
Joined: Tue Jul 15, 2008 10:50 pm
Location: Carolina, USA

Re: Reading a CSV file

Post by omniuni »

What about http://us2.php.net/fgetcsv ??

Doesn't that kind of do what you need?
Jeeee
Forum Newbie
Posts: 10
Joined: Sun Aug 03, 2008 11:18 am

Re: Reading a CSV file

Post by Jeeee »

Thank you both for your help. It's greatly appreciated!

Cheers
Post Reply