简体   繁体   中英

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

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);

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

$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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM