简体   繁体   English

如何限制while循环中的项目

[英]How to limit items from while loop

This is my while loop from my project : 这是我的项目中的while循环:

<?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? 正如您已经知道的那样,这个while循环将循环访问他们在我的数据库中找到的所有项目,所以我的问题是,如何仅针对我的数据库中的10个项目限制此循环以及如何在每次刷新时旋转这些项目?

In SQL: 在SQL中:

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

or in PHP: 或者在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. 关于旋转,请参阅@Fayden的回答。

Rotate as in random, or as the next 10 elements ? 随机旋转,还是作为接下来的10个元素?

Most RDBMS allow you to order rows by random : 大多数RDBMS允许您随机排序行:

-- 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 每次刷新页面时都会选择10个随机行

If you want to show the next 10 elements, you would have to paginate the page (and use the LIMIT X OFFSET Y syntax) 如果要显示接下来的10个元素,则必须对页面进行分页(并使用LIMIT X OFFSET Y语法)

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,如果您只需要10个第一项,请尝试使用LIMIT为10,如果需要对结果进行分页,请尝试使用OFFSET

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

Then you need to control the $start and $range variables like: 然后你需要控制$ start$ range变量,如:

$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 您可以注意到$ range应该与$ size_page的值相同,只需要考虑#pages计算每次迭代的$ start值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM