如何在while循环中分页?

时间:2011-02-10 05:15:36

标签: mysql pagination while-loop

我基本上需要通过while循环从数据库中获取一些视频信息并将它们放入div中。唯一的问题是我需要在a和tag之间一次只放6个,然后让它进入下一个6等等。这是我的代码:

$count = 0; 
$sql = "SELECT * FROM videos ORDER BY id DESC";
$result_set = $database->query($sql);
while($videos = $database->fetch_array($result_set)) {
$count++;
    // i know this is horribly wrong...
if($count == 0 || (($count % 6)+1 == 1)) {
    echo '<div>';
}
    // i need 6 videos to go in between the <div> and </div> tags then go on to another 6
    echo "<a href=\"video/{$videos}\">{$videos['title']}</a>";


if($count == 0 || (($count % 6)+1 == 1)) {
    echo '<div>';
}           
}

1 个答案:

答案 0 :(得分:1)

这是做你想做的事的有效方法:

$resultPerPage = 6;
$count = 0;
$sql = "SELECT * FROM videos ORDER BY id DESC";
$result_set = $database->query($sql);
$noPage = 1;

echo '<div id="page_1" class="pages">';
while($videos = $database->fetch_array($result_set)) {
    $count++;
    echo "<a href=\"video/{$videos}\">{$videos['title']}</a>";
    if($count == $resultPerPage) {
        echo '</div><div id="page_' . $noPage++ . '" class="pages">';
        $count=0;
    }       
}
echo '</div>';