In the previous part you have learned how to send
commands (SQL queries) to a database from within a PHP script. This is a very important
step because now you know all the core pieces needed to build a web application.
In the previous exercises, you have made a script which prints various lists of
persons using the print_r function. Although functional, this is plain ugly.
To create a reasonably formtted list, you need to modify your script to output
a HTML page. Although you should already know everything necessary, I feel that
you might appreciate a little guidance.
Task – Print Data in HTML
A big task lies ahead of you. Print first_name, last_name, nickname and
age rounded to years of all persons ordered by last_name and first_name (ascending).
Print the persons in a HTML table, one row each. Use a
layout template for the HTML page.
Again, approach the task in steps, e.g.:
Make a static HTML page with some sample data (skip this if you are confident with templates).
Make a PHP script to print the page using templates.
Make the data in the script dynamic – load it from a variable, make sure the variable has the same
format as obtained from the database.
Modify the PHP script to load the variable from the database.
No one is forcing you to take all the above steps separately or in the shown order.
But you must always be able to divide a complex task into simpler steps. This
is really important – the scripts will become only more and more complicated and there is really
only one way to be oriented in all the code and debug it. You have to split it into smaller pieces,
write and test the pieces individually. Notice how – in the above steps – I have changed only one thing
at a time. Some parts (like the template layout) don’t need to be changed at all. However splitting
the code requires you to understand the connections between all the code parts:
In this chapter, you have learned how to use SQL queries from within a PHP script and
output the result into a HTML page.
Because the entire application code is now becoming a bit complex, it is really important that
you are able to separate the code into individual parts and test each part individually.