user1421688
user1421688

Reputation: 43

import data from CSV into mysql table using php

I'm trying to import a csv file in my mysql table. This is my code:

<?

error_reporting(0);
mysql_connect("localhost","root","");
mysql_select_db("gerov");


$filename='test.csv';

$handle = fopen("$filename", "r");
while (($data = fgetcsv($handle, ",")) !== FALSE)
//foreach(fgetcsv($handle,",") as $data)
{
$import="INSERT into castigatori (id,cod,nume,oras,medalie) values('','$data[0]','$data[1]','$data[2]','$data[3]')";
mysql_query($import) or die("mysql_error()");
print $import."<br>";
}
fclose($handle);
print "Import done";

?> 

The import it's done ok but only if I put a comma between each word in the csv file. So if I want to insert a,b,c,d it will only import if I put those commas between them. I want to write the words on a separate cell like this: a b c d without having to put the comma and making a tab delimited between the words. If I write the words with tab delimited, in my mysql table will show up like this : a ;b ;c ;d. Can anyone tell me what to do in order to insert them correctly?

Upvotes: 2

Views: 1994

Answers (2)

Ruel
Ruel

Reputation: 15780

EDIT:

If you want the delimiter to be a space, then:

fgetcsv($handle, 0, " ")

Upvotes: 0

Ondra Žižka
Ondra Žižka

Reputation: 46796

MySQL offers LOAD DATA INFILE.
Check http://dev.mysql.com/doc/refman/5.1/en/load-data.html .
Especially:

    [{FIELDS | COLUMNS}
    [TERMINATED BY 'string']
    [[OPTIONALLY] ENCLOSED BY 'char']
    [ESCAPED BY 'char']

Upvotes: 2

Related Questions