Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to limit items from while loop

Tags:

php

while-loop

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?

like image 653
Zhaf Avatar asked Oct 23 '10 21:10

Zhaf


People also ask

How do I limit a while loop in Python?

You can keep a counter of guesses , e.g. guesses = 0 . Then, at the end of your while_loop, guesses += 1 . Your condition can be while guesses < 3 for example, to limit it to 3 guesses.

How do I limit in PHP?

Limit Data Selections From a MySQL Database Assume we wish to select all records from 1 - 30 (inclusive) from a table called "Orders". The SQL query would then look like this: $sql = "SELECT * FROM Orders LIMIT 30"; When the SQL query above is run, it will return the first 30 records.

What describes the danger of a while loop in Java?

One of the most common errors you can run into working with while loops is the dreaded infinite loop. You risk getting trapped in an infinite while loop if the statements within the loop body never render the boolean eventually untrue.

When would you use a while loop?

A "While" Loop is used to repeat a specific block of code an unknown number of times, until a condition is met. For example, if we want to ask a user for a number between 1 and 10, we don't know how many times the user may enter a larger number, so we keep asking "while the number is not between 1 and 10".


2 Answers

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.

like image 171
Pekka Avatar answered Oct 14 '22 21:10

Pekka


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)

like image 38
Vincent Savard Avatar answered Oct 14 '22 23:10

Vincent Savard