I got this code and for some reason $i++ doesn't work.It shows everything in the database and i just want 10 elements to be shown
if($i <= 10){
while($row = mysqli_fetch_assoc($result)){
echo '<li>'.$row['title'].'</li>';
$i++;
}
}
A quick fix, change:
if($i <= 10){
while($row = mysqli_fetch_assoc($result)){
echo '<li>'.$row['title'].'</li>';
$i++;
}
}
...to:
while($i <= 10 && $row = mysqli_fetch_assoc($result)){
echo '<li>'.$row['title'].'</li>';
$i++;
}
Explanation:
Once you're in the if
conditional block, that if
condition never gets evaluated again. Only the while
condition gets evaluated with each loop, so move the $i <= 10
into the while
condition. Use an AND &&
because you want both conditions to be true to continue looping.
But, ya, as Fred -ii- suggest, adding LIMIT 10
to your database query would reduce the amount of data you have to handle.
You should limit the result on your MySql
query with LIMIT 10
.MySql
LIMIT tutorial
i.e.:
select something from something LIMIT 10;
Answering to your direct question:
Use break:
$i = 1;
while($row = mysqli_fetch_assoc($result)) {
echo '<li>'.$row['title'].'</li>';
$i++;
if($i > 10) {
break;
}
}
break ends execution of the current
for
,foreach
,while
,do-while
orswitch
structure.