Using a script I found in this forum
I managed to import a csv file into a MySQL table. I need assistance to work out one bug. Some of the lines in the csv file contain commas. When a line contains commas, the data doesn't go into the right columns starting from the first column with contained a comma.
How can I work around this?
The code for my import (based on the thread mentioned above) is below
Thanks in advance,
MrsBean
I managed to import a csv file into a MySQL table. I need assistance to work out one bug. Some of the lines in the csv file contain commas. When a line contains commas, the data doesn't go into the right columns starting from the first column with contained a comma.
How can I work around this?
The code for my import (based on the thread mentioned above) is below
Thanks in advance,
MrsBean
Code:
//empty out the import (temporary) table
$sql = "delete from ImportMemberUpdate ";
$result = MYSQL_QUERY($sql);
$filename = "ImportMemberUpdate.csv";
$fp = fopen($filename, "r") or die("Failed to open flat file");
echo "Opened flat file ok...<br>";
flock($fp, LOCK_EX); // lock the file while we got it open
// the first line of the csv usually contains
// the descriptions of the columns. We don't want
// to write this into the db so set a flag
//note - I left this in, but it doesnt work
//the first line (column names) gets imported
$firstline = true;
// now we read each line and write that to the database
while (!feof($fp)){
if ($firstline) {
// skip this iteration of the while loop
// and carry on with next line
$firstline = false;
continue;
}
// read this line
$line = fgets($fp,16384);
// remove any ' and replace with `
$line = str_replace("'", "`", $line);
// next split this line into it's componates
$delim = ",";
$data = explode($delim, $line);
// now $data will be an array contining
// all the fields. eg the first field will be
// $data[0] and the second $data[1] etc
// do any processing you want with these now
// now we have all the luvly data ...
$sql = "insert into ImportMemberUpdate values (";
$sql .= $data[0] . ", " ; // a numberic value
$sql .= "'" . $data[1] . "', "; // a string
$sql .= "'" . $data[2] . "', "; // a string
snipped part of the code
$sql .= "'" . $data[29] . "')"; // the last value
// remember that string value must be enclosed in
// quotes ' and numeric don't
echo "<p>$sql</p>";
$result = mysql_query($sql) ;
}
echo "all done we hope! <br>";
flock($fp, LOCK_UN); // unlock the file