如何使用 PHP 执行多个 mysql 查询

How to execute many mysql queries with PHP

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

例如:

<?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";
?>

如果我有 1'000 或 10'000 个用户,一切都很好。

但我想知道,如果我有 100,000 个用户(或更多),我应该怎么做才能避免服务器错误/内存限制?

有办法拆分我的脚本吗?

考虑使用 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'" );
?>

永远不要在大循环中执行查询,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";
?>

使用mysqlINSERT .... SELECT

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