Jump to content

Importing CSV file as array


cavey5

Recommended Posts

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?

Link to comment
https://forums.phpfreaks.com/topic/62366-importing-csv-file-as-array/
Share on other sites

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.