Eventually, we’ll learn a strategy called “routing” that makes creating
new pages easier and gives you tons of control over how your URLs look.
Every page follows a familiar pattern: we do some work at the top - like querying
the database - and then we use the variables we created in the rest of the
HTML to print things. Here, our “work” will be to query for only one pet
in the database.
But first, let’s create a link from each pet on the homepage to this file.
To tell the page which pet we want to display, let’s add ?id= to the end
of the URL and print out this pet’s id:
The HTTP request coming into the server now contains a little extra information
via this query parameter. So how can we read this in PHP? Whenever you need
some data from the incoming request, the answer is always one of those
superglobal variables. We used $_POST to get data submitted in a
form and $_SERVER to figure out if this is a GET or POST request.
Query parameters are accessed via the $_GET superglobal. Let’s dump this
Just like the other superglobals, this is an associative array. We can add
more values in the URL by adding an & sign between each:
You know the drill from here! We’ll query the database for this one pet and
use that information to build the page. But wait! Should we build the query
right here or put it in a function? Easy choice: a function will help keep
things organized. Call an imaginary get_pet() function and pass it the
And before we even think about creating that function, we already know what
it will return: an associative array with the details for just one pet.
Let’s build out this page with that in mind. To save some typing, I’ve started
this file in the code download at resources/episode3/show.php. I’ll copy
its contents into this middle of our page and fill in a few missing pieces: