i am trying to upload .csv file where user can browse the file and upload the file and the data gets inserted into mysql db.but the 1st row of the .csv file getting inserted in table as that row contain the column names respectively.here is my code
<?php
//Connect to Database
if (isset($_POST['submit'])) {
if (is_uploaded_file($_FILES['filename']['tmp_name'])) {
echo "<h1>" . "File ". $_FILES['filename']['name'] ." uploaded successfully." . "</h1>";
}
//Import uploaded file to Database
$handle = fopen($_FILES['filename']['tmp_name'], "r");
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
//db connection
$import="INSERT into csv(id,user,phone) values('$data[0]','$data[1]','$data[2]')";
mysql_query($import) or die(mysql_error());
}
fclose($handle);
print "Import done";
}else {
echo "sorry";
}
?>
my table structure
CREATE TABLE `csv` (
id int(10) NOT NULL DEFAULT '0',
user varchar(10) NOT NULL,
phone int(10) NOT NULL
) ENGINE=InnoDB DEFAULT CHARSET=latin1
$handle = fopen($_FILES['filename']['tmp_name'], "r");
fgetcsv($handle, 1000, ","); // pop the headers
while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) ...
Just call fgetcsv
once before you start looping through the rest.
In fact, I usually use this idiom:
$fh = fopen(...);
$headers = fgetcsv($fh);
while ($row = fgetcsv($fh)) {
$row = array_combine($headers, $row);
echo $row['columnname'];
}
It allows your to access columns by name, instead of by index.