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?
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.
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.
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.
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".
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.
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With