duanhan9334 2013-08-27 07:29
浏览 135
已采纳

是否有使用for循环插入多个查询的替代方法

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

  • 写回答

3条回答 默认 最新

  • dongtu1789 2013-08-27 07:40
    关注

    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);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 使用C#,asp.net读取Excel文件并保存到Oracle数据库
  • ¥15 C# datagridview 单元格显示进度及值
  • ¥15 thinkphp6配合social login单点登录问题
  • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
  • ¥15 如何在scanpy上做差异基因和通路富集?
  • ¥20 关于#硬件工程#的问题,请各位专家解答!
  • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
  • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
  • ¥30 虚心请教几个问题,小生先有礼了
  • ¥30 截图中的mathematics程序转换成matlab