Reputation: 569
I'm using a while loop to display the data in a sql table and group the data from each row within a list item. I need the loop to stop after displaying 50 rows from the sql table. If it's helpful, $id is unique and for each row.
<?php
include("db.php");
$query="SELECT * FROM `stories`";
$result=mysqli_query($connection,$query);
?>
<li>
<?php
while ($data = mysqli_fetch_assoc($result)):
$id = $data['id'];
$img_link = $data['img_link'];
$page_path = $data['page_path'];
$tag_alt = $data['tag_alt'];
$category = $data['category'];
if(is_null($page_path)){$page_path = "#";}
?>
<img alt="<?php echo $tag_alt; ?>" src="<?php echo $img_link; ?>" width="200" height="200">
<h3><a href="#"><?php echo $title; ?></a></h3>
<a href="categories/<?php echo $category; ?>.html"><label> </label><?php echo $category; ?></a></span>
<p><?php echo $tag_alt; ?></p>
</li>
<?php
endwhile;
mysqli_close($connection);
?>
Upvotes: 0
Views: 875
Reputation: 569
Thank you for everyones help here. Using the LIMIT function seemed to work best. I added BETWEEN and RAND to improve functionality.
<?php include("db.php"); $query="SELECT * FROM `stories` WHERE id BETWEEN 1 AND 200 order by RAND() LIMIT 20"; $result=mysqli_query($connection,$query); ?
Thank you again, nothing beats the talented service found on StackOverflow
Upvotes: 1
Reputation: 4584
In the query you can give like this.
(In case of sqlserver):
$query="SELECT TOP 50 * FROM `stories`";
(In case of Mysql or postgre):
$query="SELECT * FROM `stories` LIMIT 50 ";
If you want to show results 51 to 100 in next page, you should pass page number or counter to a page, as well as u should change your sql a little bit.
Upvotes: 2
Reputation: 3470
The ideal way should be make a query with a 50 limit
$query="SELECT * FROM `stories` LIMIT 50 ";
But if for some reason you need your array after in the same page and you only want to show in this case the first 50, you can do something like:
while ($data = mysqli_fetch_assoc($result)){
$array[]=$data;
}
for($i=0;$i<=49;$i++){
$id = $array[$i]['id'];
//etc...
}
Upvotes: 1
Reputation: 349
Is it your solution??
$i=1;
while ($data = mysqli_fetch_assoc($result) && $i <= 50):
{
//Code Here
$i++;
}
Upvotes: 1
Reputation: 9635
first option is you can use LIMIT 50
like this
$query="SELECT * FROM `stories` LIMIT 50";
The second one is you can maintain a counter variable if you don't want to use LIMIT 50
<?php
$counter = 0;
while ($data = mysqli_fetch_assoc($result))
{
$counter+=1;
$id = $data['id'];
$img_link = $data['img_link'];
if($counter>50)
{
break;
}
Upvotes: 3
Reputation: 340
$query="SELECT * FROM `stories`";
replace it with
$query="SELECT * FROM `stories` LIMIT 50 ";
Upvotes: 0