嵌套的 Foreach 循环花费太多时间

Nested Foreach loop taking too much time

我正在使用 Nested Foreach 循环将数据存储在 mysql 中。但是它花费了太多的处理时间。我怎样才能减少最大执行时间。

foreach ($results as $r) {
    mysqli_query($con,"insert into commercial values('".mysqli_real_escape_string($con,$r['MST_MLS_NUMBER'])."')");
    $val=1;
    $objects = $rets->GetObject('Property', 'Photo', $r['MST_MLS_NUMBER'], '*', 0);
    foreach ($objects as $pho) {
        mysqli_query($con,"insert into cmtval values('".mysqli_real_escape_string($con,$r['MST_MLS_NUMBER'])."')");
    }
}

你应该使用bulk insert

INSERT INTO tbl_name (a,b,c) VALUES(1,2,3),(4,5,6),(7,8,9);

通过 foreach 循环,您应该首先执行查询,然后使用 mysqli_query.

执行查询
$query1 = "insert into commercial values ";
$query2 = "insert into cmtval values ";
foreach ($results as $r)
{
     $query1 .= "('" . mysqli_real_escape_string( $con, $r['MST_MLS_NUMBER']) . "'), ";

     $val=1;
$objects = $rets->GetObject('Property', 'Photo', $r['MST_MLS_NUMBER'], '*', 0);
  foreach ($objects as $pho)
  {
     $query2 .= "('" . mysqli_real_escape_string( $con, $r['MST_MLS_NUMBER']) . "'), ";
  }
}

mysqli_query($con, $query1);
mysqli_query($con, $query2);

我还没有测试过代码。测试并让我知道是否缺少任何东西。 批量更新减少了一些时间。

此外,如果您在单个查询中在数据库中保存了太多数据,并且索引太多,则插入数据需要时间。

你可以做这样的东西

foreach ($results as $r)
{
  mysqli_query($con,"insert into commercial values('".mysqli_real_escape_string($con,$r['MST_MLS_NUMBER'])."')");

    $val=1;
    $objects = $rets->GetObject('Property', 'Photo', $r['MST_MLS_NUMBER'], '*', 0);


    // generate partial query strings for insert multiple records
    $numbers=array();
    foreach ($objects as $pho)
    {
        $numbers[]= "('".mysqli_real_escape_string($con,$pho['MST_MLS_NUMBER'])."')";

    }

    mysqli_query($con,"insert into cmtval values".implode(",",$numbers)); // it will insert multiple record 
}

您可以使用准备语句并使用要插入的不同值执行

例如

// prepare and bind
$stmt = $conn->prepare("INSERT INTO MyGuests (firstname, lastname, email) VALUES (?, ?, ?)");
$stmt->bind_param("sss", $firstname, $lastname, $email);

// set parameters and execute
$firstname = "John";
$lastname = "Doe";
$email = "john@example.com";
$stmt->execute();

$firstname = "Mary";
$lastname = "Moe";
$email = "mary@example.com";
$stmt->execute();

$firstname = "Julie";
$lastname = "Dooley";
$email = "julie@example.com";
$stmt->execute();

设置参数和执行行应该在你的 foreach 循环中。

准备好的语句和绑定参数 准备好的语句是一种用于高效地重复执行相同(或相似)SQL语句的功能。

Prepared statements basically work like this:

Prepare: An SQL statement template is created and sent to the database. Certain values are left unspecified, called parameters (labeled "?"). Example: INSERT INTO MyGuests VALUES(?, ?, ?) The database parses, compiles, and performs query optimization on the SQL statement template, and stores the result without executing it Execute: At a later time, the application binds the values to the parameters, and the database executes the statement. The application may execute the statement as many times as it wants with different values