【问题标题】:replicate/duplicate/clone a mysql_result object复制/复制/克隆一个 mysql_result 对象
【发布时间】:2019-11-18 22:21:57
【问题描述】:

我正在尝试将 mysql SELECT 查询保存到文件中,如下所示:

$result = mysqli_query($db,$sql);

$out = fopen('tmp/csv.csv', 'w');
while ($row = $result -> fetch_row()) {
fputcsv($out,$row);
    }
fclose($out);

保存后我需要在页面上发布如下:

while ($row = mysqli_fetch_assoc($result)) {
//embed html code
}

问题是每当我运行 $result->fetch_row() 时,都会丢失一条数据记录。我需要能够在我的代码中运行 fetch_object 至少 2 次并保留数据。我认为克隆会是一个很好的解决方案,但事实并非如此。

除了对 sql 数据库进行 2 次查询之外的任何提示?

【问题讨论】:

    标签: php mysql object clone


    【解决方案1】:

    我相信另一种可行的解决方案是使用mysqli_data_seek

    mysqli_result 对象是一个指针,每次调用 fetch_row() 时都会在数据中移动,但您可以通过调用将指针移回开头

    mysqli_data_seek($result, 0);
    

    现在结果是“重置”,你可以再次使用它。

    在此处了解更多信息:

    https://www.php.net/manual/en/mysqli-result.data-seek.php

    【讨论】:

    • 这行得通,也是最简单的方法,因为不需要补丁,所有旧代码保持不变。
    【解决方案2】:

    如果您需要重复使用数据,请将其加载到数组中 - 或在同一个循环中执行所有逻辑。

    例如,

    $data = []:
    $result = $mysqli->query("...");
    while ($row = mysqli_fetch_assoc($result)) {
        $data[] = $row;
    }
    
    $out = fopen('tmp/csv.csv', 'w');
    foreach ($data as $row) {
        fputcsv($out, $row);
    }
    fclose($out);
    
    // ...
    
    foreach ($data as $row) {
        //embed html code
    }
    

    或者在同一个循环中执行所有操作(这可能并不总是可行,所以如果不是,请使用上面的选项)。

    $result = mysqli_query($db, $sql);
    
    $out = fopen('tmp/csv.csv', 'w');
    while ($row = $result->fetch_row()) {
        fputcsv($out,$row);
        // embed HTML
    
    }
    fclose($out);
    

    【讨论】:

      【解决方案3】:

      如果您已将 mysqlind 作为 PHP MySQL 基础架构的一部分安装,请使用 fetch_all() 将所有结果放入数组中。然后,您可以根据需要多次使用该数组。

      $result = mysqli_query($db,$sql);
      $all_results = $result->fetch_all();
      
      $out = fopen('tmp/csv.csv', 'w');
      
      foreach ( $all_results as $row){
          fputcsv($out,$row);
      }
      fclose($out);
      
      // now to reuse the array for your HTML output
      foreach ($all_results as $row) {
          //embed html code
      }
      

      然后你可以重复使用$all_results

      如果你没有mysqlind,那么编写一个简单的循环来手动加载一个数组,其中包含结果集中的所有结果

      $result = mysqli_query($db,$sql);
      $all_results = [];
      while ($row = $result -> fetch_assoc()) {
          $all_results[] = $row;
      }
      
      $out = fopen('tmp/csv.csv', 'w');
      
      foreach ( $all_results as $row){
          fputcsv($out,$row);
      }
      fclose($out);
      
      // now to reuse the array for your HTML output
      foreach ($all_results as $row) {
          //embed html code
      }
      

      【讨论】:

        猜你喜欢
        • 2011-04-15
        • 2013-04-06
        • 2011-10-17
        • 2013-02-18
        • 2011-03-29
        • 2015-01-08
        • 2011-10-21
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多