monkey coder
monkey coder

Reputation: 163

How to update variable before while loop

I have a variable named post_counter, and I want to get the value of it after it finished the loop, and I want it as the first list item to display. but the problem is the php only read the variable as 0 because the compiler read the codes from top to bottom. how can i update my counter? this is my php code:

$post_counter = 0;
<ul>
<?php
$query_post = "SELECT post_date,post_message FROM tbl_posts";
$post_run = mysqli_query($con,$query_post);
echo "<li style = 'text-align:center; cursor:default'><h3>"."New posts".$post_counter."</h3></li>";
while($row = mysqli_fetch_assoc($post_run))
{
    echo "<li><a class = 'mark_read'>"."mark as read"."</a></li>";
    $post_counter++;
}
?>
</ul>

the output of this will be:

New posts 0

but it should be

New posts 5 //since there are 5 rows in my table that will be selected

Upvotes: 0

Views: 55

Answers (1)

John Conde
John Conde

Reputation: 219824

Use mysqli_num_rows()

$post_run = mysqli_query($con,$query_post);
$num_posts = mysqli_num_rows($postrun);
echo "<li style = 'text-align:center; cursor:default'><h3>"."New posts".$num_posts ."</h3></li>";

Upvotes: 3

Related Questions