How to Iterate a Block of HTML

Take for example this blog. It is repeating the same chunk of HTML for each post I make. The only difference is the content. If you were to look at the page source, it would appear as though the developer copied the code for the first post, and pasted it several times, replacing only the content in each iteration. That however, would be a very inefficient process (it is how I did it before I learned PHP) and is called a static page. To make this page dynamically generate a block of HTML for each post saved in a database we can use a loop (a very basic knowledge of PHP and MySQL will be assumed).

Here is an example of a block of HTML that we might want to iterate (the part between the “items” tags):

By placing a for loop (line 2) around the block of HTML and including the row fetch (line 4) inside the loop we can make it iterate and though our entire database (in this case displaying a picture and a name in each HTML block):

I will reiterate (no pun intended) that the row fetch must be inside the for loop for this to work, otherwise it will repeat the first row of the database over and over again.

Leave a Reply

Wordpress theme JaeDubya © 2018 | All Right Reserved | Designed & coded by J. Arthur Wetenkamp