Jump to content

Importing data with csv files


proba1

Recommended Posts

Hello guys i am new here. I have troubles with inserting data from csv file.

I want to insert from csv file data but distribution of columns is not in the same order like in database.

 

For example :

 

table: contact

columns: contact_first,contact_last, contact_email

 

,but in csv file order is in the opposite order :

contact_email,contact_last,contact_first

or doesn't matter can be in random order.

 

Thanks in advance,

Maja

Link to comment
Share on other sites

Actually you are using fgetcsv to READ the incoming data.

 

As I said in my other response to you, the incoming data must be in a recognizable order or you can not do this. Whether the data has identifiers within it or there is a row of headers at the start, either way. But to be completely random is not possible.

 

I have to wonder how this data was prepared for you with no thought given as to how it would be used.

Link to comment
Share on other sites


$csv = fopen('my.csv', 'r');
$data = array();

while (list($contact_email, $contact_last, $contact_first) = fgetcsv($csv, 1024)) {
$data[] = "('$contact_first', '$contact_last', '$contact_email')"; // order matches SQL INSERT order
}

fclose($csv);

// use multiple insert
$sql = "INSERT INTO contact (contact_first,contact_last, contact_email) VALUES ";
$sql .= join(',', $data);
$mysqli->query($sql);

Link to comment
Share on other sites

Barand has provided some great code that normally would be perfect for you Proba. But as you said originally the input can be in 'random order' so this code will not work. Are you sure the input is in "random order"? Seems strange to have a process that produces random input like you describe.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.