How to limit items from while loop

断了今生、忘了曾经 提交于 2019-12-07 11:34:03

问题


This is my while loop from my project :

<?php
   $select = "SELECT * FROM nk_showcase";
   $query = $db->rq($select);
   while ($user = $db->fetch($query)) {
?>

    <div class="index">
        <a href="details.php?id=<?php echo $user['id']; ?>"><img width="200" height="171" alt="<?php echo $user['title']; ?>" src="<?php echo $url; ?>/images/niagakit/<?php echo $user['thumb']; ?>"/></a>
        <h3><a href="<?php echo $url; ?>/"><?php echo $user['title']; ?></a></h3>
        <p><a href="<?php echo $url; ?>/"><?php echo $user['url']; ?></a></p>
    </div>

<?php } ?>

As you already know, this while loop will loop for all items they found in my database, so my quuestion is, how to limit this loop only for 10 items only from my database and how to rotate that items every refresh?


回答1:


In SQL:

$select = "SELECT * FROM nk_showcase LIMIT 0,10";

or in PHP:

$counter = 0;
$max = 10;

 while (($user = $db->fetch($query)) and ($counter < $max))
  {
   ... // HTML code here....

   $counter++;
  }

As to the rotating, see @Fayden's answer.




回答2:


Rotate as in random, or as the next 10 elements ?

Most RDBMS allow you to order rows by random :

-- MySQL
SELECT * FROM nk_showcase ORDER BY RAND() LIMIT 10
-- PostgreSQL
SELECT * FROM nk_showcase ORDER BY RANDOM() LIMIT 10

Which would select 10 random rows every time you refresh the page

If you want to show the next 10 elements, you would have to paginate the page (and use the LIMIT X OFFSET Y syntax)




回答3:


You have to change your query $select, try using LIMIT to 10 if you just need the 10 first items or try also with OFFSET if you need to paginate the results.

$select.=" OFFSET $start LIMIT $range;";

Then you need to control the $start and $range variables like:

$size_page=10;
 if (!$page) {
             $start = 0;
             $page=1;
        }
        else {
            $start = ($page - 1) * $size_page;
        } 

You can notice that $range should be the same value of $size_page and just you need to calculate the $start value for each iteration taking into account the #pages



来源:https://stackoverflow.com/questions/4006069/how-to-limit-items-from-while-loop

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!