Have you ever seen a URL which looked like www.example.com/page.php?mode=1&style=red
? Well, this page is being passed variables and their values through the query string, here the variables mode
and style
are being passed, with values 1
and red
respectively. The question mark ?
indicates the start of the query string and the ampersand, &
, symbol separates variable=value assignments. The page is then able to read these variables and react according to them, for example to display them to the user.
Passing a query string to a page
There are two ways to pass a query string to a page, the first is to enter it manually, for example:
The above HTML creates a link to a page passing the variable mode with the value 1
.
An alternative, and perhaps more useful, way is to use HTML forms. The main thing to remember with forms is that you need to use the GET method to send information via the query string, for example:
This code displays a simple HTML form with a text box and a submit button. When the user enters their name and presses submit, the information in the name box is passed to a page called “page.php” (specified in the form’s action attribute) via the query string. So, if I entered moose
and pressed submit, the form will call page.php?username=moose
. Remember that username
was what we entered as the text input’s name attribute.
Accessing a query string element in a PHP page
In PHP, all the information passed via the query string is held in the $_GET
super global array (prior to PHP version 4.1.0 it was called $HTTP_GET_VARS
, but that’s now depreciated). To access an item, type $_GET['varName']
, where varName is the name of the variable in the query string. To demonstrate, let’s create page.php to process the information from the form above:
So now, me typing in moose and pressing submit will generate the reply “Hello, moose”.
Listing the contents of $_GET
Should you wish to find out everything that’s in the query string, you can do so with the following code which displays the variables next to their values in a table: