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条)

报告相同问题?

悬赏问题

  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 对于相关问题的求解与代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 信号傅里叶变换在matlab上遇到的小问题请求帮助
  • ¥15 保护模式-系统加载-段寄存器
  • ¥15 电脑桌面设定一个区域禁止鼠标操作
  • ¥15 求NPF226060磁芯的详细资料