Reputation: 13
I don't understand why they exit the while loop in the code below. I have tried to check on google but the answer was not given.
The PHP tag was closed before
<h1 class="page-header">
and this was
<?php } ?>
added at the end of the code to close the loop. Can someone please explain to me so I can have a better understanding of the code. Thanks.
<?php
$query = "SELECT * FROM post";
$select_all_post_query = mysqli_query($connection, $query);
while($row = mysqli_fetch_assoc ($select_all_post_query)){
$post_title = $row['post_title'];
$post_author = $row['post_author'];
$post_date = $row['post_date'];
$post_image = $row['post_image'];
$post_content = $row['post_content'];
?>
<h1 class="page-header">
Page Heading
<small>Secondary Text</small>
</h1>
<!-- First Blog Post -->
<h2>
<a href="#"><?php echo $post_title ?></a>
</h2>
<p class="lead">
by <a href="index.php"><?php echo $post_author ?></a>
</p>
<p><span class="glyphicon glyphicon-time"></span> <?php echo $post_date ?></p>
<hr>
<img class="img-responsive" src="http://placehold.it/900x300" alt="">
<hr>
<p><?php echo $post_content ?></p>
<a class="btn btn-primary" href="#">Read More <span class="glyphicon glyphicon-chevron-right"></span></a>
<hr>
<?php }
?>
Upvotes: 0
Views: 69
Reputation: 1120
A key point of PHP is, that you can mix it up with HTML to generate server-side dynamically HTML.
The first PHP-Block is just some ceremonial code, that introduces some variables in a while loop, which will be echoed out later on amidst the HTML as one can see here:
<!-- First Blog Post -->
<h2>
<a href="#"><?php echo $post_title ?></a>
</h2>
They keep the while loop
open since they want to render one blog post per iteration of the while loop
.
Everything between:
while($row = mysqli_fetch_assoc ($select_all_post_query)){
$post_title = $row['post_title'];
$post_author = $row['post_author'];
$post_date = $row['post_date'];
$post_image = $row['post_image'];
$post_content = $row['post_content'];
?>
And the closing:
<?php }
?>
which is essentially this:
<h1 class="page-header">
Page Heading
<small>Secondary Text</small>
</h1>
<!-- First Blog Post -->
<h2>
<a href="#"><?php echo $post_title ?></a>
</h2>
<p class="lead">
by <a href="index.php"><?php echo $post_author ?></a>
</p>
<p><span class="glyphicon glyphicon-time"></span> <?php echo $post_date ?></p>
<hr>
<img class="img-responsive" src="http://placehold.it/900x300" alt="">
<hr>
<p><?php echo $post_content ?></p>
<a class="btn btn-primary" href="#">Read More <span class="glyphicon glyphicon-chevron-right"></span></a>
<hr>
will get echoed out as HTML once per iteration of the while loop. This leads to there being multiple blog posts on one HTML page.
Upvotes: 0
Reputation: 405975
The HTML between the two PHP tags is part of the loop. As the loop iterates, that HTML should be emitted to the page multiple times (assuming there are multiple results returned by the query).
Upvotes: 1