Reputation: 1
I want a while that fills up a table with database information but just as often as rows exist but max. 5 times if there are more than 5 rows it should echo a show more button This one outputs everything that is in the table
while($row = $statement->fetch()) {
echo "<tr>";
echo '<td><a href="http://example.com/'.$row['id'].'">example.com/'.$row['id'].'</a></td>';
echo "</tr>";
}
and this one outputs it 5 times but even if there is nothing
for($i=1; $i <= 5; $i++; &&$row = $statement->fetch()) {
echo "<tr>";
echo '<td><a href="http://example.com/'.$row['id'].'">example.com/'.$row['id'].'</a></td>';
echo "</tr>";
}
I hav
e tried something with mysqli_num_rows but it didn't work too
Upvotes: 0
Views: 28
Reputation: 94672
Amend your query and add LIMIT 5
at the end of it. This will only return a MAX of 5 rows, less if there are less rows that satisfy your where clause. This will also stop you returning 1000 rows and only using 5 of them, thus reducing wasted network traffic.
Then use your while
loop as that will consume all the result set, and there will never be more than 5 rows to consume.
while($row = $statement->fetch()) {
Answer to your comment:
I did say put the LIMIT 5
at the end of your query !
$statement = $pdo->prepare("SELECT *
FROM link
WHERE userid= $uid
AND only = 'true'
LIMIT 5");
Upvotes: 1