PHP Query Strings
In this chapter you will learn:
- Why do we need Query Strings
- Example - create query string
- Note for query string
- Example - Access data in the query string
Description
Query strings are not limited to form data. A query string is a string stored in a URL, we can manually create a URL containing a query string in PHP script, then include the URL as a link within the displayed page.
Example
Here's 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:
<?PHP/*j a va 2 s.co m*/
$firstName = "Jack";
$age = "34";
$queryString = "firstName=$firstName&age=$age";
echo '<a href="index.php?' . $queryString . '"> Find out more info</a>';
?>
The code above generates the following result.
If the user then clicks this link, index.php is run, and the query string data (firstName=John & age=34 ) is passed to the index.php script. Data has been transmitted from one script execution to the next.
Note
Note that the ampersand (&) character needs to be encoded as & inside XHTML markup.
Example 2
To access the field names and values in a query string, read them from the $_GET superglobal array.
$firstName = $_GET["firstName"];
$homePage = $_GET["homePage"];
So it's easy to write a simple version of the index.php script referenced in the previous example:
<?php // ja v a2 s . c o m
$firstName = $_GET["firstName"];
$homePage = $_GET["homePage"];
$favoriteSport = $_GET["favoriteSport"];
echo "$firstName \n";
echo "$homePage \n";
echo "$favoriteSport \n";
?>
Next chapter...
What you will learn in the next chapter: