I am using the code below to import a CSV textfile into my table, but my new host not allowing LOAD DATA
commands and forces me to find alternative ways of importing the file. Naturally, they are useless in giving me a clear answer.
What other ways except LOAD DATA LOCAL
and LOAD DATA
do I have to import a CSV file into my MySQL table via PHP/MySQLi?
// Query - import CSV file into DB, ignore top 3 lines
$sql= "LOAD DATA LOCAL INFILE '".$import_file."' INTO TABLE `$dbtable`
FIELDS TERMINATED BY '".$fieldseparator."'
LINES TERMINATED BY '".$lineseparator."'
IGNORE 3 LINES
SET TIMESTAMP = '".$local_time."'";
Thanks
EDIT:
After looking into the suggested fgetcsv
function, I came up with the below code. Theoretically, it should work, but the code seems to load until it finally times out without showing an error. The database is populated with a single row entry only.
What am I doing wrong here?
if ($import_file) {
// set row counter to 0
$line = 0;
while ( ($row = fgetcsv($import_file)) !== false ) {
// ignore the first 3 rows of the file based on iteration of the counter
if ($line <= 3) {
$line++;
continue;
} else {
// if row count is higher than 3, insert into database
$sql = "INSERT INTO `$dbtable`
(`OPERA_CONF`, `CRS`, `HOLIDEX`, `ARRIVAL`)
VALUES (
'" . $row[0] . "',
'" . $row[1] . "',
'" . $row[2] . "',
'" . $row[3] . "'
)";
// execute query
$mysqli->query($sql);
$line++;
}
}
} else {
echo "
CSV file could not be found.";
}