[英]How to get the next row in mysqli result?
我想在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...
} ?>
不确定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
}
}
关于以下内容如何:
SELECT * FROM table WHERE id > '$currentID' ORDER BY id LIMIT 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>";
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.