【问题标题】:How to get the next row in mysqli result?如何获得mysqli结果的下一行?
【发布时间】:2013-06-03 21:27:30
【问题描述】:

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

【问题讨论】:

  • 我认为你不能“偷看”下一个结果。最好的办法是加载所有结果,然后使用 for 循环对其进行迭代。
  • 您可以将每一行存储在一个数组中,然后循环遍历该数组。不理想,但它会工作
  • 我想知道如果没有“下一个”结果会发生什么。哪里都没有结果。

标签: php mysql list mysqli associative-array


【解决方案1】:

不确定是否使用 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
  }
}

【讨论】:

  • 我不相信这将适用于 mysqli,不幸的是
  • 嗯,是的,mysqli 中没有 fetchall。你的第二个答案是我所知道的唯一开箱即用的方法。 (mysqli打击)
  • 有一个MySQLi版本的fetch all :) php.net/manual/en/mysqli-result.fetch-all.php
【解决方案2】:

关于这行的东西怎么样:

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

获取下一个可能的行。

【讨论】:

    【解决方案3】:

    看看这个解决方案,你怎么看?它有效,但会更慢?这个算法至少需要双关吗?你觉得呢?

    $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>";
    

    【讨论】:

    • 我认为它太臃肿了,而且——以我的拙见——毫无用处。
    • 这个想法是为打印 html 树创建一个无用的函数:只需调用函数 tree( $data );它将编写html结构和元素。 'next' 和 'previous' 属性便于您在使用 javascript (jquery) 时了解您的位置
    • 它应该分为两部分:获取数据的函数和打印树的函数,后者完全独立于数据源。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-10-05
    • 1970-01-01
    • 2020-08-20
    相关资源
    最近更新 更多