dongzice4895 2017-03-17 11:58
浏览 199
已采纳

使用mysqli_fetch_assoc()时如何在php中获取下一行MySQL查询而不进行操作

I am trying to run a query to my mysql database through php and and am trying to get all the resulting rows. I also have to compare every row to the next row returned. I am trying to do this by setting the result variable to another temporary variable and calling mysqli_fetch_assoc() on that so that the while loop runs again for the next row. But what happens is that when I try to use mysqli_fetch_assoc() even on the other variables, somehow mysqli_fetch_assoc($result) also progresses to the next of the next row when while($row = mysqli_fetch_assoc($result)) goes to next iteration.

Here is the code example to illustrate this :

$query = "SELECT * FROM records ORDER BY num ASC;";
    if($result = mysqli_query($conn, $query))
    {
       while($row = mysqli_fetch_assoc($result))
       {
         $temporaryresult = $result;
         $rowtwo = mysqli_fetch_assoc($temporaryresult);// this makes mysqli_fetch_assoc($result) skip the next row which is unwanted
       }
    }

So how can I keep mysqli_fetch_assoc($result) from moving forward when I call mysqli_fetch_assoc($temporaryresult) ?

Any help would be appreciated.

  • 写回答

2条回答 默认 最新

  • dpsr1670 2017-03-17 12:48
    关注

    After @CBroe's answer, I tried to solve this problem while still trying to look forward. I achieved this by storing the rows returned by the database and then looping through them. This makes it very easy too look ahead in the rows returned while avoiding the complexity of changing your code to look backwards.

    $array = array(); 
    // look through query
    while($row = mysql_fetch_assoc($query)){    
      // add each row returned into an array
    
      $array[] = $row;
    
    }
    

    Now, looping through these rows,

    $i = 0;
    for(;$i<count($array)-1;$i++)
    {
       if($array[$i]['somecolumn']==$array[$i+1]['anothercolumn'])//compare this column to another column in the next row
       {
          // do something
       }
    } 
    

    This successfully solved my problem. I hope it helps anyone stuck in the same position I was in.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 虚幻5 UE美术毛发渲染
  • ¥15 CVRP 图论 物流运输优化
  • ¥15 Tableau online 嵌入ppt失败
  • ¥100 支付宝网页转账系统不识别账号
  • ¥15 基于单片机的靶位控制系统
  • ¥15 真我手机蓝牙传输进度消息被关闭了,怎么打开?(关键词-消息通知)
  • ¥15 装 pytorch 的时候出了好多问题,遇到这种情况怎么处理?
  • ¥20 IOS游览器某宝手机网页版自动立即购买JavaScript脚本
  • ¥15 手机接入宽带网线,如何释放宽带全部速度
  • ¥30 关于#r语言#的问题:如何对R语言中mfgarch包中构建的garch-midas模型进行样本内长期波动率预测和样本外长期波动率预测