I am quite new to PHP and need your help for an issue. I will explain my problem in the following steps:
1- I have a CSV file and I would like to import it to MySQL database with PHP.
2- When I add commas at the end of each lines in the CSV file, I could import it by using IMPORT option in Mysql db. I can not import it without adding commas at the end of lines.
3- I want to add a new line into my PHP code which will add commas at the end of each record/line and will enable the data imported without any error.
Here is my code:
<?php
//read file
$csvfile=file_get_contents("/samba/import/Tbl_HRList.csv");
$lines = explode(PHP_EOL, $csvfile);
$array = array();
foreach ($lines as $line) {
$field = str_getcsv($line);
if ($field[0] != ''){
$sql="INSERT INTO HR_Tbl (Employee_ID, First Name, Prefix, Surname, Location, Organizational Code, Organizational Unit, Team, Team Code, Function, Function code, T24 Department Code, Date in service (GBI), Company email, End Date Contract, End Date Systems, Temp. Leave Date, Temp. Leave End, Temp. Leave Code)
VALUES
('$field[0]','$field[1]','$field[2]','$field[3]','$field[4]','$field[5]','$field[6]','$field[7]','$field[8]','$field[9]','$field[10]','$field[11]','$field[12]','$field[13]','$field[14]','$field[15]','$field[16]','$field[17]','$field[18])";
}
//insert record to database
if ($conn->query($sql) === TRUE) {
echo "New record created successfully". PHP_EOL;
} else {
echo "Error: " . $sql . "<br>" . $conn->error;
}
}
else
{
continue;
}
}
$conn->close();
?>
Thanks in advance Alex