1

I am importing data from csv file so I used that code

<?php
$path = "Export.csv";
$row = 1;
if (($handle = fopen($path, "r")) !== FALSE) {
    while (($data = fgetcsv($handle, 1000, ",")) !== FALSE) {
        $row++;
        $data_entries[] = $data ;


    }
    fclose($handle);
}
 echo"<pre>";
 print_r($data_entries);
 echo"</pre>";
?>

and my array output like that my first array showing column names after that all array showing value so i want to insert value base on first array column names

 Array
 (
  [0] => Array
    (
        [0] => Type
        [1] => PinCode
        [2] => APN
        [3] => County
    )
  [1] => Array
    (
        [0] => Auction
        [1] => 503082537
        [2] => 502-052-002
        [3] => United States of America
    )
  [2] => Array
    (
        [0] => Auction
        [1] => 21596378
        [2] => 628-202-038
        [3] => Australia
     )
 )
2
  • What is the expected result ? Commented Aug 17, 2012 at 5:51
  • i want to run query like that insert into table(Type,PinCode,APN,County)values('Auction',503082537,502-052-002,'United States of America')............insert into table(Type,PinCode,APN,County)values('Auction',21596378 ,628-202-038,'Australia') ) Commented Aug 17, 2012 at 5:55

2 Answers 2

3

Try the below code :

//extract the column names
$fields = array_shift($data_entries);
$values = array();

// Append the values
foreach($data_entries as $value){
   $values[]="('{$value[0]}', '{$value[1]}', '{$value[2]}', '{$value[3]}' )";
}

// Build the SQL
$sql = "INSERT INTO `TABLE_NAME` (" . implode(',' , $fields) . ") values " . implode(',', $values);
Sign up to request clarification or add additional context in comments.

1 Comment

i have 60 column in table i have to expand it like that $values[]="('{$value[0]}', '{$value[1]}', '{$value[2]}', '{$value[3]}','{$value[4]}' )"; there is any way dont need to expand it '{$value[60]}'
0

You might try a different approach, since your data is coming from a CSV file.

LOAD DATA LOCAL INFILE 'Export.csv' INTO TABLE YourTable;

There are many options, read the manual: http://dev.mysql.com/doc/refman/5.0/en/load-data.html

Comments

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.