Dalton Pereira
Dalton Pereira

Reputation: 1061

is there an alternate to using a for loop to insert multiple queries

I want to insert data from an array. Below is an example situation.

I grab all my friends available in friends list (fb) and store them in an array.

Now I want to insert their data ( name, fbid, birthday ) into a table.

Currently I'm doing this using a for loop below is an example code.

<?php

  $friendsname = $_POST['name'];
  $friendsfbid = $_POST['fbid'];
  $friendsbday = $_POST['birthday'];

  for($i<0;count($friendsfbid);$i++){

     $sql_query  = "INSERT INTO table (fbid, name, birthday) VALUES ('$friendsfbid[$i]','$friendsname[$i]','$friendsbday[$i]') ON DUPLICATE KEY UPDATE fbid='$friendsfbid[$i]', name='$friendsname[$i]', birthday='$friendsbday[$i]'";    

  }

?>

Now if I have 300 friends this will loop 300 times.

The more number of friends the more time its going to take to process the data.

Is there a way to avoid this or to increase the performance of the code. ?

Using PHP with mySQL

Upvotes: 1

Views: 7314

Answers (3)

Praveen Prasannan
Praveen Prasannan

Reputation: 7123

Insert multiple rows at a time. See this example:

INSERT INTO example
  (example_id, name, value, other_value)
VALUES
  (100, 'Name 1', 'Value 1', 'Other 1'),
  (101, 'Name 2', 'Value 2', 'Other 2'),
  (102, 'Name 3', 'Value 3', 'Other 3'),
  (103, 'Name 4', 'Value 4', 'Other 4');

Loop through php to generate the multiple rows data and issue a single insert at last appending the multiple rows

Upvotes: 2

Dejv
Dejv

Reputation: 954

$sql = '';
foreach($friendsfbid as $key => $value){
   $sql .= INSERT INTO table (fbid, name, birthday) VALUES ('$value[$key]','$friendsname[$key]','$friendsbday[$key]') ON DUPLICATE KEY UPDATE fbid='$value[$key]', name='$friendsname[$key]', birthday='$friendsbday[$key]'";
}
mysql_query($sql);

You can stack your sql INSERTs into string and then run them by calling query function only once. That should speed the process up.

Upvotes: 1

Prasannjit
Prasannjit

Reputation: 795

Please See this query hope this will be improve our code and speed.

Avoid doing SQL queries within a loop

A common mistake is placing a SQL query inside of a loop. This results in multiple round trips to the database, and significantly slower scripts. In the example below, you can change the loop to build a single SQL query and insert all of your users at once.

foreach ($userList as $user) {

  $query = 'INSERT INTO users (first_name,last_name) VALUES("' . $user['first_name'] . '", "' . $user['last_name'] . '")';

  mysql_query($query);

  }

Instead of using a loop, you can combine the data into a single database query.

$userData = array();

foreach ($userList as $user) {

    $userData[] = '("' . $user['first_name'] . '", "' . $user['last_name'] . '")';

}

$query = 'INSERT INTO users (first_name,last_name) VALUES' . implode(',', $userData);

mysql_query($query);

Upvotes: 5

Related Questions