Reputation: 79
im using bootstrap and my main index page is in php, i have been trying to dynamically display data from my database but i only want to display 5 of the rows in my database table.
echo '<ul class="sort" id="rank_ul">';
$res = mysql_query("SELECT * FROM IFC ORDER BY votes DESC");
while($row=mysql_fetch_assoc($res))
{?>
<li id="li<?php echo $row['id']?>">
<div class="tut-img">
<img src="<?php echo $row['img']?>" width="50" height="70" alt="<?php echo $row['title']?>" />
<div class="drag-label"></div>
</div>
<div class="title">
<a href="<?php echo $row['url']?>" target="_blank" title=""><?php echo $row['title']?></a>
</div>
</li>
<?php }?>
</ul>
essentially my code is creating as many list items as there are rows in my data, but i would like to make it stop creating list items at a specific number of times, the issue i had was that i wanted to keep it in descending order and switching from a while loop to a for loop or do-while didnt create the list items.
Upvotes: 2
Views: 101
Reputation: 2067
The simplest (and best) way would be to add a LIMIT
clause to your query like so:
$res = mysql_query("SELECT * FROM IFC ORDER BY votes DESC LIMIT 5");
As a side note, I highly recommend using either PDO or MySQLi instead of the old, deprecated MySQL extension.
Upvotes: 1
Reputation: 42490
You could solve the problem in you PHP code, of course, but the cleanest way would be to only fetch the entries from the database you actually need.
Using MySQL's LIMIT
clause, you can specify how many rows you want to select:
SELECT * FROM IFC ORDER BY votes DESC LIMIT 50
In this case, only 50 rows will be selected and echoed by your code.
On a side node, please be aware that the mysql PHP extension is deprecated since PHP 5.5.x. Please use mysqli or PDO instead.
Upvotes: 0