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

Recommended Answers

All 3 Replies

Member Avatar for rajarajan2017

Try this:

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

Also check whether $arr has the contents.

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) ."')";

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..

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.