如何用PHP执行许多mysql查询

时间:2015-01-24 15:50:06

标签: php mysql loops while-loop split

假设我有一个名为“users”的mysql表,而且我经常需要在另一个mysql表中为每个用户插入一条记录。

例如:

<?php
$result = mysqli_query( $c,"SELECT user_id FROM users WHERE '$search'" );
while( $array = mysqli_fetch_array( $result ) ) {
  // execute a query for each users
  mysqli_query( $c,"INSERT INTO example ( id, user_id, record1, record2, date ) VALUES ( NULL, '$array[user_id]', '$record1', '$record2', '$date' )" );
  $count++;
}
echo "$count rows added";
?>

如果我有1000或1000个用户,一切都很棒。

但我想知道,如果我有100,000个用户(甚至更多),我该如何避免服务器错误/内存限制?

有一种方法来分割我的脚本吗?

3 个答案:

答案 0 :(得分:3)

考虑使用INSERT ... SELECT命令。

<?php
    $result = mysqli_query( $c,"INSERT INTO example ( id, user_id, record1, record2, date ) SELECT NULL, user_id, '$record1', '$record2', '$date' FROM users WHERE '$search'" );
?>

答案 1 :(得分:3)

使用mysql INSERT .... SELECT

mysqli_query($c,"INSERT INTO example (id, user_id, record1, record2, date)
SELECT NULL, user_id, '$record1', '$record2', '$date' FROM 
users WHERE '$search'");

答案 2 :(得分:0)

永远不要在大循环中执行查询,1000已经是一个非常糟糕的主意:

<?php
$result = mysqli_query( $c,"SELECT user_id FROM users WHERE '$search'" );
$insert = array();
while( $array = mysqli_fetch_array( $result ) ) {
  // execute a query for each users
  $insert[] = "( NULL, '$array[user_id]', '$record1', '$record2', '$date' )";
}
mysqli_query( $c,"INSERT INTO example ( id, user_id, record1, record2, date ) VALUES " . implode(', ', $insert) );
echo count($insert) . " rows added";
?>