How to use the query string in PHP?

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:

<a href="page.php?mode=1">Mode 1</a>

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:

<form method="GET" action="page.php">
  Please enter your name: 
  <input type="text" name="username" />
  <input type="submit" value="submit" />
</form>

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 usernamewas 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:

<?php
if($_GET['username'] == "") {
  // no username entered
  echo "You did not enter a name.";
} else {
  echo "Hello, " . $_GET['username'];
}
?>

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:

<table border="1">
  <tr>
    <th>variable</th>
    <th>value</th>
  </tr>
  <?php
    foreach($_GET as $variable => $value) {
      echo "<tr><td>" . $variable . "</td>";
      echo "<td>" . $value . "</td>";
    }
  ?>
</table>

Leave a Reply

Your email address will not be published. Required fields are marked *