2

I want to import csv file to mysql database and I am getting an error in it that I am not able to fix. please help me to find what is the issue..

my code is

    <?php 
if(isset($_POST['submit']))
{   

$connect = mysql_connect('127.0.0.1','root','');


if (!$connect) {
 die('Could not connect to MySQL: ' . mysql_error());
 }
$cid =mysql_select_db('ts_order_track',$connect);

$file = $_FILES['file']['tmp_name'];
if ($_FILES["file"]["error"] > 0)
{
echo "Error: " . $_FILES["file"]["error"] . "<br />";
}

else {


echo "hi";
        $q="LOAD DATA INFILE '$file' INTO TABLE tsd_orders
        FIELDS TERMINATED BY ',' ENCLOSED BY '"'
        LINES TERMINATED BY '\n' 
        IGNORE 1 LINES
        ( order_id, customer_id, firstname, lastname, email, telephone, mobile, shipping_firstname, shipping_lastname, shipping_mobile, shipping_address_1, shipping_address_2, shipping_city, shipping_zone, shipping_postcode, shipping_country, shipping_method, payment_method, payment_code, weight, date_added, date_modified, import_order_id, sub_total, shipping_charges, tax_charges, total, order_status, courier, awb_code, coupon_amount, coupon_code, product_name, product_sku, product_model, product_quantity, product_price )";
        $s=mysql_query($q, $connect );

echo "File data successfully imported to database!!"; 
   } 



mysql_close ( $connect );
}
?>

And the error is

Parse error: syntax error, unexpected '' ' (T_CONSTANT_ENCAPSED_STRING) in C:\xampp\htdocs\try.php

please help me to find the error and what should be the code here..

this is my csv file

order_id,customer_id,firstname,lastname,email,telephone,mobile,shipping_firstname,shipping_lastname,shipping_mobile,shipping_address_1,shipping_address_2,shipping_city,shipping_zone,shipping_postcode,shipping_country,shipping_method,payment_method,payment_code,weight,date_added,date_modified,import_order_id,sub_total,shipping_charges,tax_charges,total,order_status,courier,awb_code,coupon_amount,coupon_code,product_name,product_sku,product_model,product_quantity,product_price
3605600753,68,Deepali,Agni,deepali@trendspry.com,8800311993,8800311993,Deepali,Agni,8800311993,sushant Lok,Shopping Arc,GGN,Haryana,122001,India,Free shipping,Cash on Delivery,cod,0.50kg,28-05-2015,28-05-2015,bhg9,1299,0,0,1299,Pending,NA,NA,0,NA,A Beautiful  Black And Yellow Georgette Saree,BR19891153,Georgette and Jacquard Embroidery and Printed Casual and Office ,1,1299

1 Answers1

0

You need to escape the newline character \n and the double quotation " in your query:

$q="LOAD DATA INFILE '$file' INTO TABLE tsd_orders
    FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '\"'
    LINES TERMINATED BY '\\n' 
    IGNORE 1 LINES
    ...

Have a look at this SO post for a syntactically-correct way to use LOAD DATA inside a PHP script.

Community
  • 1
  • 1
Tim Biegeleisen
  • 502,043
  • 27
  • 286
  • 360