有没有使用for循环插入多个查询的替代方法 [英] is there an alternate to using a for loop to insert multiple queries

查看:107
本文介绍了有没有使用for循环插入多个查询的替代方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从数组中插入数据.下面是一个示例情况.

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

我抓住了好友列表(fb)中所有可用的朋友,并将它们存储在一个数组中.

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

现在,我要将其数据(name, fbid, birthday)插入表中.

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

当前,我正在使用for循环执行此操作,下面是示例代码.

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]'";    

  }

?>

现在,如果我有300个朋友,它将循环300次.

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

将PHP与mySQL一起使用

Using PHP with mySQL

推荐答案

请参阅此查询,希望这将提高我们的代码和速度.

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

避免在循环中执行SQL查询

Avoid doing SQL queries within a loop

一个常见的错误是将SQL查询放入循环内.这导致数据库多次往返,并且脚本速度明显降低.在下面的示例中,您可以更改循环以构建单个SQL查询并一次插入所有用户.

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

这篇关于有没有使用for循环插入多个查询的替代方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆