Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

load data infile, dealing with fields with comma

How do we deal with field with comma when using load data infile? i have this query:

$sql = "LOAD DATA LOCAL INFILE '{$file}' INTO TABLE sales_per_pgs 
        FIELDS TERMINATED BY ','
        LINES TERMINATED BY '\n'
        IGNORE 1 LINES
        (@user_id, @account_code, @pg_code, @sales_value)
        SET
        user_id = @user_id, 
        account_code = @account_code,
        product_group_code = @pg_code,
        sales_value = REPLACE(@sales_value, ',', ''),
        company_id = {$company_id},
        year = {$year},
        month = {$month}";

and a line from the csv looks like this:

139, pg89898, op89890, 1,000,000.00

where 1,000,000.00 is a sales value.

Currently, what is inserted in my database is only "1.

EDIT

The user downloads a form with columns like:

user id, account id, pg id, sales value

where the first three columns user id, account id, pg id, were populated and the sales value column is blank because the user has to fill it up manually... the user uses MS excel to do that...

after the form is completed, he will now upload it, in which i am using the load data infile command...

like image 294
Mico Avatar asked Aug 01 '12 12:08

Mico


1 Answers

Your content should really look like:

"139", "pg89898", "op89890", "1,000,000.00"

Then you could add the following to the command:

ENCLOSED BY '"' ESCAPED BY "\\"

And you won't have an issue.

Also, somethign you could try if you don't have any paragraphs or strings with , in them:

FIELDS TERMINATED BY ', '
like image 61
Mike Mackintosh Avatar answered Oct 03 '22 20:10

Mike Mackintosh