【问题标题】:How to get next record inside the mysql result dataset?如何在 mysql 结果数据集中获取下一条记录?
【发布时间】:2012-03-24 20:47:52
【问题描述】:

Mysql 给了我们一个数据集 当我们在 mysql 中运行一个 select 查询,我们使用 while 或 for 循环语句从这个数据集中获取每条记录。我想知道当我们在没有到达循环顶部的情况下获取记录时,是否有任何函数可以获取该数据集中的下一条记录? 类似:

$result = mysql_query("SELECT * FROM table1");
while ($row = mysql_fetch_array($result)) {

 $currentId = $row['id'];
 $nextId = mysql_fetch_next()['id'];
 ......

}

??

【问题讨论】:

  • 这样做的目的是什么?为什么不在下一个循环中获取值>
  • 因为我想为每一个设置prev和next。

标签: php mysql dataset


【解决方案1】:

我会添加另一个迭代,将您的资源转换为一个数组,并且还包括下一个 ID(假设它不一定是前一个 ID + 1,在这种情况下这一切都毫无意义):

$recordset = array(); $i = 0;
while ($row = mysql_fetch_assoc($result))
{
    $recordset[$i] = $row;
    if ($i > 0) { $recordset[$i-1]['nextid'] = $row['id']; }
    $i++;
}

那么你可以将 $recordset 用于任何目的。

【讨论】:

    【解决方案2】:
    $result = mysql_query("SELECT MAX(id) FROM `table1` GROUP BY id");
    
    if(mysql_num_rows($result) > 0){
        while($row = mysql_fetch_array($result)){
            $next = $row['MAX(id)'] + 1;
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2014-11-08
      • 1970-01-01
      • 2010-11-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多