I am trying to import a csv file, comma delimited, into MySql database. This is my script:
$fcontents = file ('./importfile.csv');
for($i=0; $i<sizeof($fcontents); $i++) {
$line = trim($fcontents[$i]);
$arr = explode(",", $line);
$sql = "insert into books values ('".
implode("','", $arr) ."')";
mysql_query($sql);
echo $sql ."<br>\n";
if(mysql_error()) {
echo mysql_error() ."<br>\n";
}
}
These are the column titles in the database and the fields in MySql:
AUTHOR TITLE ISBN BOOKFORMAT FIRST SIGNED PUBLISHER PUBDATE PUBPLACE COPIES RATING CONDITION CATEGORY READ VALUE COMMENTS DATEENTERED SOURCE LCCN DEWEY USERNUMBER COPYRIGHTDATE VALUEDATE LOCATION SERIES PAGES KEYWORDS DIMENSIONS
Here is the first record:
"Abernethy, Robert G.","Introduction to tomorrow; the United States and the wider world, 1945-1965 [by] Robert G. Abernethy","","","N","N","Harcourt","1966","New York","1","","","History, Modern -- 1945-1989","N","2.50","Bibliographical references included in &doublequote;Notes&doublequote; (p. 265-274)","2009-05-15","Library of Congress [1]","66011195","909.82","","","2009-05-15","B1","","286","History, Modern -- 1945-1989, United States -- Foreign relations -- 1945-1989",", maps, ports. 22 cm."
Here is the output.
insert into books values ('"Abernethy',' Robert G."','"Introduction to tomorrow; the United States and the wider world',' 1945-1965 [by] Robert G. Abernethy"','','','N','N','Harcourt','1966','New York','1','','','"History',' Modern -- 1945-1989"','N','2.5','Bibliographical references included in &doublequote;Notes&doublequote; (p. 265-274)','5/15/2009','Library of Congress [1]','66011195','909.82','','','5/15/2009','B1','','286','"History',' Modern -- 1945-1989',' United States -- Foreign relations -- 1945-1989"','"',' maps',' ports. 22 cm."')
Column count doesn't match value count at row 1
How can I make this work? I think it is the commas causing the problem, or perhaps the quotes but this database is what it is and I cannot change the way it is done. Can I use addslashes or something to make it work properly?