0

我想在 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...
} ?>
4

3 回答 3

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
  }
}
于 2013-06-03T21:32:19.507 回答
0

关于这行的东西怎么样:

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

获得下一个可能的行。

于 2017-05-25T09:27:04.160 回答
-1

Look at this solution, what do you think about it? it works, but will be more slow? this algorithm requires at least double pass or not? what do you think?

$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>";
于 2013-06-04T13:47:33.317 回答