问题
Mysql gives us a dataset When we run a select query in mysql and we use while or for loop statement to get each record from this dataset. I want to know is there any function to get the next record inside this dataset when we get a record without reach the top of the loop? something like:
$result = mysql_query("SELECT * FROM table1");
while ($row = mysql_fetch_array($result)) {
$currentId = $row['id'];
$nextId = mysql_fetch_next()['id'];
......
}
??
回答1:
I would add another iteration that converts your resource into an array and also includes the next ID (assuming it's not necessarily the previous ID + 1, in which case this is all pointless):
$recordset = array(); $i = 0;
while ($row = mysql_fetch_assoc($result))
{
$recordset[$i] = $row;
if ($i > 0) { $recordset[$i-1]['nextid'] = $row['id']; }
$i++;
}
Then you can use $recordset for whatever purpose.
回答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;
}
}
来源:https://stackoverflow.com/questions/9599542/how-to-get-next-record-inside-the-mysql-result-dataset