2

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?

2 Answers 2

2

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']
Sign up to request clarification or add additional context in comments.

Comments

0

EDIT:

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

fgetcsv($handle, 0, " ")

3 Comments

I changed this: while (($data = fgetcsv($handle, ",")) !== FALSE) to this: while (($data = fgetcsv($handle)) !== FALSE) but not in my table the words are inserted like this: a; b; c; d;
a, b, c, d this is a line in my csv file. This way the words are inserted ok my table each word with his column but I want without those commas. What do I need to change.
My bad, the delimiter is the 3rd parameter. Try it now.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.