Practical 08: Introducing PHP into HTML
In this practical activity, we will be utilizing different sets of data in PHP variables to modify how a webpage appears.
We will only be dabbling with one PHP file, namely
Additional styles are provided as embedded CSS here.
If you're not sure how to set up your machine for PHP development, or where to place your files and how to open the files from that location, I strongly advise you to check out setting up XAMPP here. You may need to look elsewhere if you have anything else other than XAMPP or MAMP.
index.php like as follows:
You should see the following output:
Note that the table as shown here does not have any other rows displayed aside from the header row.
We will now have PHP utilize the array values as stored in the following PHP code block to populate the table.
Place the following PHP block on top of
Add the following code block in between the
The code block that's provided here makes use of a for loop to iterate over the elements in the array.
The for loop as shown here makes it so that a new
<tr> row element along with its
<td> elements are created during each iteration.
Since there are 4 items in the array, the for loop ends up creating 4 rows of data.
The highlighted lines show that a PHP block can be prematurely broken to encapsulate HTML code as part of your program control structure's block. This will apply for all loop structures and conditional statements.
You may also notice that in between lines 5 to 7, they make use of special expression tags that are purposed to print out the values of expressions and/or PHP variables. Let's see this in action again.
Create an empty
<h1></h1> tag before the table in your HTML, and add the following variable in the top PHP block:
Hence or otherwise, add the value of
$heading in the newly-created
<h1></h1> element. You should now see something like as follows:
Back to the Activity Narrative
With PHP, you can also create different views with conditional statements. Add one more PHP variable in the top PHP block:
Modify the webpage so that the heading and table only appear if
Otherwise, the webpage should display this message in a single (and separate)
We will use program control structures more extensively in the next practical exercise. By now, hopefully you understand how to leverage PHP to prepare different views based on conditions.