Query Strings

Somewhat more flexible is the query string, which is attached to the end of the URL in a link. A query string can consist of as many name/value pairs as you (the developer) want to supply. The big difference is that PHP provides a means by which the user can supply values that can be embedded in the query string. Say, for example, that the user has entered a value of John as his first name, and your PHP program can make use of that value via its variable name ($first_name, for instance).

You could write a PHP program that generates a query string attached to a URL using code such as this (assuming you had the $first_name and $last_name variables already set):

<a href="http://www.myplace.com?first_name=<?php echo $first_name; ?>">Click

When this code runs, it produces the following output:

<a href="http://www.myplace.com?first_name=John">Click Here</a>

Notice how a query string is constructed: a question mark followed by the name of the first name/value pair, an equals sign, and the value in the first name/value pair. If you had both a first name and a last name, you could have included both name/value pairs in the query string by connecting them with an ampersand (&), like so:

<a href="http://www.myplace.com?first_name=<?php echo $first_name;
?>&last_name=<?php echo $last_name; ?>">Click Here</a>

Putting both name/value pairs in the query string would result in the following (if you're a dead movie star):

<a href="http://www.myplace.com?first_name=John&last_name=Wayne">Click

Query strings are often useful (especially in preserving values between page requests, which are discussed that a bit more later in the chapter), but as you can see they are still quite limited. For one thing, to place a user-supplied value in a query string, you have to already have it. You could get it from a database, but if you needed to get it from the user before using it, you'd have to provide the user with some free form method of supplying it. And that brings us to a very powerful method for user interaction, the HTML form.