Forum Moderators: coopster

Message Too Old, No Replies

inserting a csv file into a mysql database

         

fintan

9:11 am on Jun 3, 2004 (gmt 0)

10+ Year Member



Hi all

I'm trying to insert data from a csv file into a mysql database. Here's what I got so far.

$csvfle = "phgrades.csv";

$opnfle = fopen($csvfle, "r");

$inscsv = "insert into phgrades (gradecode, grade, gradeclass, gradepoint, grouping, rank) VALUES ('$row[0]','$row[1]','$row[2]','$row[3]','$row[4]','$row[5]','$row[6]')";

while(!feof($opnfle)){

$row = fgetcsv($opnfle, 1024, ";");

$rslt = mysql_query($inscsv);

}

Is there anything I'm missing? Thanks

fintan.

ergophobe

2:18 pm on Jun 3, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member Top Contributors Of The Month



At the time that you create your query ($inscsv), $row is undefined.

You need to grab the row, then assign the values.

If queries aren't working, echo them before querying

echo $inscsv;
$rslt = mysql_query($inscsv);

I suspect that if you do this, you'll find that your query is not what you think.

If you get it so the query looks good and still doesn't work, I prefer to debug in the mysql client rather than through php. That way you know exactly what query you're using and can more easily figure out how to debug.

Tom

fintan

3:09 pm on Jun 3, 2004 (gmt 0)

10+ Year Member



Thanks Tom for the reply

I see what you mean. I tried this instead


while(!feof($opnfle))
{
$row = fgetcsv($opnfle, 1028 , ";");

$inscsv = "insert into phgrades (gradecode, grade, gradeclass, gradepoint, grouping, rank) VALUES ('$row[0]','$row[1]','$row[2]','$row[3]','$row[4]','$row[5]','$row[6]')";

mysql_query($inscsv);
echo $inscsv."<br><br>\n\n";
}

I guess I made a boo boo. Thanks

fintan.

jatar_k

7:11 pm on Jun 3, 2004 (gmt 0)

WebmasterWorld Administrator 10+ Year Member



also since fgetcsv returns false at EOF you can just have this

while($row = fgetcsv($opnfle, 1028 , ";")) {
etc..

fintan

10:52 am on Jun 4, 2004 (gmt 0)

10+ Year Member



Thanks for the tip jatar_k

timster

1:07 pm on Jun 4, 2004 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



I'm trying to insert data from a csv file into a mysql database.

Just a question -- Is there a reason you need to get PHP involved in this import? mysqlimport is faster and pretty easy.

[dev.mysql.com...]

fintan

1:52 pm on Jun 4, 2004 (gmt 0)

10+ Year Member



More than likely but I wanted to setup a cron job to load the file every night.