cavey5 Posted July 29, 2007 Share Posted July 29, 2007 I have a huge csv file that I need to import into an empty SQL table. First though I am testing this with a small file. I made a CSV file that only has 5 records, and 6 fields. I used the script I found here by searching but I get an error... check it out. <?php $row = 1; $handle = fopen("file.csv", "r"); while (($data = fgetcsv($handle, 5, ",")) !== FALSE) { $num = count($data); echo "<p> $num fields in line $row: <br /></p>\n"; $row++; $SQLq =""; for ($c=0; $c < $num; $c++) { echo $data[$c] . "<br />\n"; $SQLq .= "$data[$c],"; } $SQLq = trim($SQLq, ","); //---- database $dbhost = 'localhost'; $dbusername = 'import'; $dbpasswd = 'password'; $database_name = 'import'; $connection = mysql_pconnect("$dbhost","$dbusername","$dbpasswd") or die ("Couldn't connect to server."); $db = mysql_select_db("$database_name", $connection) or die("Couldn't select database."); $query = "INSERT INTO table (fname, lname, address, city, state, zip) VALUES ($SQLq)"; echo $query; $sql = mysql_query($query) or die (mysql_error()); //--- database } //<--this one to close the while loop fclose($handle); ?> What I get is this (and no data inserted): 1 fields in line 1: fnam INSERT INTO table (fname,lname,address,city,state,zip) VALUES (fnam)You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'table (fname,lname,address,city,state,zip) VALUES (fnam)' at line 1 any ideas where I have gone wrong? Quote Link to comment https://forums.phpfreaks.com/topic/62366-importing-csv-file-as-array/ Share on other sites More sharing options...
cavey5 Posted July 29, 2007 Author Share Posted July 29, 2007 Also, what does the "r" mean here? $handle = fopen("file.csv", "r"); Quote Link to comment https://forums.phpfreaks.com/topic/62366-importing-csv-file-as-array/#findComment-310373 Share on other sites More sharing options...
cavey5 Posted July 29, 2007 Author Share Posted July 29, 2007 anyone? Quote Link to comment https://forums.phpfreaks.com/topic/62366-importing-csv-file-as-array/#findComment-310442 Share on other sites More sharing options...
fenway Posted July 31, 2007 Share Posted July 31, 2007 Table is a reserved keyword... fopen() opens a file. Quote Link to comment https://forums.phpfreaks.com/topic/62366-importing-csv-file-as-array/#findComment-311974 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.