簡體   English   中英

使用mysqli_fetch_assoc()時如何在不獲取進度的情況下在php中獲取MySQL查詢的下一行

[英]How to get next row of MySQL query in php without progressing when using mysqli_fetch_assoc()

我試圖通過php對我的mysql數據庫運行查詢,並試圖獲取所有結果行。 我還必須將每一行與返回的下一行進行比較。 我正在嘗試通過將結果變量設置為另一個臨時變量並在其上調用mysqli_fetch_assoc()來做到這一點,以便while循環再次為下一行運行。 但是發生的是,當我甚至嘗試對其他變量使用mysqli_fetch_assoc()時,當while($row = mysqli_fetch_assoc($result))進行下一次迭代時, mysqli_fetch_assoc($result)也會以某種方式前進到下一行的下一行。

這是代碼示例來說明這一點:

$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
       }
    }

因此,當我調用mysqli_fetch_assoc($temporaryresult)時,如何防止mysqli_fetch_assoc($result)前進?

任何幫助,將不勝感激。

我試圖通過將結果變量設置為另一個臨時變量並在其上調用mysqli_fetch_assoc()來做到這一點,以便while循環再次為下一行運行

那樣行不通。 僅僅因為您將資源ID分配給了第二個變量,並不意味着您現在有了可以單獨操作的第二個結果集。 這兩個變量都引用相同的資源ID。 提取行仍將移動“原始”數據集的行指針。

我還必須將每一行與返回的下一行進行比較

最有可能的是,您要嘗試向前看,這會使您變得更加艱難。 通常,當您查看一行時,這樣的事情通常更容易完成。 已經獲取了該文件-因此,您現在無需執行其他附加操作,而該操作會導致行指針混亂。

偽代碼示例:

$prevRow = null;
while($row = fetch(...)) {
  if($prevRow) { // for the first row, this will still be null, so we only 
                 // start comparing stuff when that is not the case
    // compare whatever you need to compare here
  }
  ...
  $prevRow = $row;
}

在@CBroe回答之后,我嘗試解決此問題,同時仍在期待。 我通過存儲數據庫返回的行,然后遍歷它們來實現這一點。 這樣就很容易在返回的行中向前看,同時避免了將代碼更改為向后看的復雜性。

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

  $array[] = $row;

}

現在,遍歷這些行,

$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
   }
} 

這成功解決了我的問題。 我希望它能幫助任何陷入我原來位置的人。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM