Page 308 - Beginning PHP 5.3
P. 308
Part III: Using PHP in Practice
In fact, PHP makes it even easier to create a query string, thanks to the handy built - in http_build_
query() function. This function take an associative array of field names and values and returns the
entire query string. You can then append this string, along with the initial ? symbol, to your URL. If
generating XHTML markup, you should also pass the string through PHP ’ s htmlspecialchars()
function, which converts, for example, & to & amp; automatically:
$fields = array (
“firstName” = > “John”,
“homePage” = > “http://www.example.com/”,
“favoriteSport” = > “Ice Hockey”
);
echo ‘ < p > < a href=”moreinfo.php?’ . htmlspecialchars( http_build_query
( $fields ) ) . ‘” > Find out more info on this person < /a > < /p > ’;
This code outputs the same markup as before:
< p > < a
href=”moreinfo.php?firstName=John & amp;homePage=http%3A%2F%2Fwww.example.com%2
F & amp;favoriteSport=Ice+Hockey” > Find out more info on this person < /a > < /p >
Accessing Data in Query Strings
As you ’ ve probably guessed by now, to access the field names and values in a query string you simply read
them from the $_GET superglobal array, just as if you were handling a form sent with the get method:
$firstName = $_GET[“firstName”];
$homePage = $_GET[“homePage”];
So it ’ s easy to write a simple version of the moreinfo.php script referenced in the previous example:
< ?php
$firstName = $_GET[“firstName”];
$homePage = $_GET[“homePage”];
$favoriteSport = $_GET[“favoriteSport”];
echo “ < dl > ”;
echo “ < dt > First name: < /dt > < dd > $firstName < /dd > ”;
echo “ < dt > Home page: < /dt > < dd > $homePage < /dd > ”;
echo “ < dt > Favorite sport: < /dt > < dd > $favoriteSport < /dd > ”;
echo “ < /dl > ”;
? >
Try It Out Square Numbers with Pagination
This example displays sequences of square numbers; that is, integers that are squares of other integers.
The script lets you view as many square numbers as you wish. It does this by using pagination — the
script displays only ten numbers at a time, but it uses query strings to create Previous Page and Next
Page links that you can use to view more numbers.
Save the following script as number_squaring.php in your document root folder, and run it in your
browser. You should see the squares of the first ten integers (0 through 9) appear. Use the Next Page
link to view the next set of ten numbers, and so on. Figure 10 - 1 shows the script in action.
270
9/21/09 9:05:08 AM
c10.indd 270 9/21/09 9:05:08 AM
c10.indd 270