Jump to content

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

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.