如何获得mysqli结果中的下一行?

时间:2013-06-03 21:27:31

标签: php mysql list mysqli associative-array

我想获取mysql结果循环中的下一行,以编写包含下一个和前一个元素代码的列表,如下例所示:

<?php $previous = null;
$next = null;
while ($row = $result->fetch_assoc()) {
$next = ??????????????? // how to get it?
?>
<li code="<?php echo $row['code']; ?>" previous="<?php echo $previous; ?>" next="<?php echo $next; ?>">Hello world!</li>
<?php
$previous = $row['code']; // previous is easy to get...
} ?>

3 个答案:

答案 0 :(得分:0)

对MySQLi不确定,但这是我在PDO中的表现方式:

$data = $stmt->fetchAll(\PDO::FETCH_ASSOC);
for($i = 0; $i < count($data); $i++) {
   $next = isset($data[$i+1]) ? $data[$i+1] : null;
}

如果 mysqli 中没有 fetchAll ,请执行:

while ($row = $result->fetch_assoc()) {
   $data[] = $row;
}

if ( ! empty($data)) {
  for($i = 0; $i < count($data); $i++) {
     $next = isset($data[$i+1]) ? $data[$i+1] : null; // next
     $prev = isset($data[$i-1]) ? $data[$i-1] : null; // previous
     $curr = isset($data[$i])   ? $data[$i]   : null; //current
  }
}

答案 1 :(得分:0)

如何做到这一点:

SELECT * FROM table WHERE id > '$currentID' ORDER BY id LIMIT 1;

获取下一个可能的行。

答案 2 :(得分:-1)

看看这个解决方案,你怎么看?它有效,但会更慢?这个算法至少要求双通?你觉得怎么样?

$db = DB::getConnection();
$result = $db->query( "SELECT * FROM objects" );

$next = null;
$previous = null;
$temp_previous = null;
$print = false;
$row = null;
$fetchit = false;
$code = null;
echo "<ul>";
while (true)
{

if ($print) {
   if ($fetchit) {
    $row = $result->fetch_assoc();
        $next = $row['code'];
   }
   echo "<li code='$code' next='$next' previous='$previous'>{$row['description']}</li>" . endl();
   $previous = $temp_previous;
   $print = false;
}
else {
 if (!$fetchit)
     $row = $result->fetch_assoc();
 $code = $row['code'];
 $temp_previous = $row['code'];
 $print = true;
 $fetchit = true;
}

if(!is_array($row)) break;

}

echo "</ul>";