Need some help. I'm uploading a CSV file with multiple records/rows and want to insert it to database using php and mysql. Please take a look on csv.
As you can see,there are three records which i want to be fetched and insert on my table.
However, when i uplaoded this file,it only returns a single array. This is the return:
["1","1","1234","12\/1\/20172","2","5678","12\/25\/20183","3","13323","1\/1\/2020"]
Can anybody help me? Here is my code:
if(isset($_POST["Import"])){
$filename=$_FILES["file"]["tmp_name"];
if($_FILES["file"]["size"] > 0)
{
$file = fopen($filename, "r");
while (($getData = fgetcsv($file, 10000, ",")) !== FALSE)
{
$sql = "INSERT INTO cardtbl (cardid,cardno,cardpin,expdate,datecreated)
VALUES ('".$getData[0]."','".$getData[1]."','".$getData[2]."','".$getData[3]."','".$today."')";
// $result = mysql_query($sql);
if(!isset($result))
{
echo "<script type=\"text/javascript\">
alert(\"Invalid File:Please Upload CSV File.\");
<!--window.location = \"cardlist.php\"-->
</script>";
}
else {
echo "<script type=\"text/javascript\">
alert(\"CSV File has been successfully Imported.\");
window.location = \"cardlist.php\"
</script>";
}
}//end
fclose($file);
}
}
Thanks!
LOAD DATA INFILE "csv_file_path"
INTO TABLE table_name
COLUMNS TERMINATED BY ','
OPTIONALLY ENCLOSED BY '"'
ESCAPED BY '"'
LINES TERMINATED BY '
'
IGNORE 1 LINES;
You can use above SQL query to insert into a table if you don't want to do any operations on the data. You can take out "IGNORE 1 LINES" string from the query if your file does not have a header. This will solve your problem.
It appears as though PHP isn't able to detect the line ending properly, it is expecting and the CSV file has
file endings (as can be seen from 12/1/2017 2).
According to the php documentation https://secure.php.net/manual/en/function.fgetcsv.php you should enable auto_detect_line_endings
by using ini_set("auto_detect_line_endings", true);
at the top of the file