Building Query Strings in PHP

Building Query Strings in PHP Query strings are not limited to form data. Query string is simply a string of characters stored in a URL, a user can manually create a URL containing a query string in the PHP script, and then include the URL as a link within the displayed page or in an email.

PHP provides some built – in functions to make the process easier.

Example

Here we will illustrate a simple example that creates two variables, $firstName and $age , then creates a link in the displayed page that contains a query string to store the variable values:

Code

$firstName = “Aman”;
$age = “26”;
$queryString = “firstName=$firstName & amp;age=$age”;
echo ‘ < p > < a href=”moreinfo.php?’ . $queryString . ‘” > Find more info about this person </a> </p> ’;

This code generates the following output

< p > < a href= “ moreinfo.php?firstName=John & amp;age=34 “ > Find more info about this person </a> </p>

If the user then clicks this link, moreinfo.php is run, and the query string data (firstName=Aman & age=26) is passed to the moreinfo.php script.

Data has been transmitted from one script execution to the next.

Remember that the ampersand ( & ) character needs to be encoded as & amp; inside XHTML markup. A user need to see that what type of characters that a user insert into the field names and values in the query string.

In Query string, only some of the characters can be used within the field name and values that are

  • Letters
  • Numbers
  • Symbols – , , . (period), ! , ~ , * , ‘ (single quote), ( , and ) .

If a user need to transmit other characters, such as spaces, curly braces, or ? characters then they should use URL encoding. This is a scheme that encodes any reserved characters as hexadecimal numbers preceded by a percent ( % ) symbol, with the exception of space characters, which are encoded as plus ( + ) signs.

PHP gives a function called urlencode() that can encode any string using URL encoding. Simply pass it a string to encode, and it returns the encoded string. So in short a user can use urlencode() function to encode any data that may contain reserved characters.

Example

$firstName = ”Aman”;
$homePage = ”http://www.example.com/”;
$favoriteSport = ”Cricket”;
$queryString = “firstName=” . urlencode( $firstName ) . “ & amp;homePage=” .
urlencode( $homePage ) . “ & amp;favoriteSport=” . urlencode( $favoriteSport );
echo ‘ <p> <a href=”moreinfo.php?’ . $queryString . ‘”> Find out info about this person </a> </p> ’;

This code generate outputs

<p><a href=”moreinfo.php?firstName=Aman & amp;homePage=http%3A%2F%2Fwww.example. com%2F & amp;favoriteSport=Cricket” > Find out info on this person </a> </p>

If a user ever need to decode a URL – encoded string then they can use the corresponding urldecode() function.