Page 1 of 1

Reading a CSV file

Posted: Sun Aug 03, 2008 11:23 am
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

Re: Reading a CSV file

Posted: Sun Aug 03, 2008 12:15 pm
by jaoudestudios
Do you have phpmyadmin? as that is all built-in

Re: Reading a CSV file

Posted: Sun Aug 03, 2008 12:28 pm
by Jeeee
Nope I'm using regular MySQL, what difference does it do if I use phpmyadmin??

Re: Reading a CSV file

Posted: Sun Aug 03, 2008 1:10 pm
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;
 

Re: Reading a CSV file

Posted: Sun Aug 03, 2008 3:29 pm
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
 
 

Re: Reading a CSV file

Posted: Sun Aug 03, 2008 9:02 pm
by omniuni
What about http://us2.php.net/fgetcsv ??

Doesn't that kind of do what you need?

Re: Reading a CSV file

Posted: Sun Aug 03, 2008 9:40 pm
by Jeeee
Thank you both for your help. It's greatly appreciated!

Cheers