0

hi

i'm trying to retrieve content from a .csv file and load it into a mysql database. i already created a corresponding table in my database with matching table names but when i try to use the following code, only one row is filled and with 0's.

<?php
$connection = mysql_connect("localhost", "root", "") or die ("Unable to connect to server");
$db = mysql_select_db("test", $connection) or die ("Unable to select database");

 #mysql connection as per the FAQ

 $fcontents = file ('test.csv');
 # expects the csv file to be in the same dir as this script

 for($i=0; $i<sizeof($fcontents); $i++) {
 $line = trim($fcontents[$i]);
 echo "$line<BR>";
 $arr = explode("\t", $line);
 echo "$arr";
 #if your data is comma separated
 # instead of tab separated,
 # change the '\t' above to ','

 $sql = "insert into customer values (". implode("'", $arr) .")";
 #$sql = "insert into test values ('". $arr ."')";
 mysql_query($sql);
 echo $sql ."<br>\n";
 if(mysql_error()) {
 echo mysql_error() ."<br>\n";
}
 }
 ?>

thanks

4
Contributors
3
Replies
4
Views
7 Years
Discussion Span
Last Post by Manuz
0

Try this:

"insert into customer values ('".implode("','",$arr)."')";

Also check whether $arr has the contents.

Edited by rajarajan07: n/a

0

Correct in part. This will add the comma's, however you still need quotes around the values. You could try:

$sql = "insert into customer values ('". implode("','", $arr) ."')";
0

Hey,
Try using LOAD DATA INFILE
eg:

LOAD DATA INFILE 'test.txt' INTO TABLE test
FIELDS TERMINATED BY ','
LINES TERMINATED BY '\n'

Just try it out..

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.