PHP - Building Query Strings

Introduction

Because a query string is a string of characters stored in a URL, you can create a URL containing a query string in your PHP script.

Then include the URL as a link within the displayed page.

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:

$firstName ="Tom" ;
$age ="3" ;
$queryString ="firstName=$firstName&age=$age" ;
echo'<p>  <a href="moreinfo.php?'. $queryString.'"> Find out more info on this person </a>  </p>';

This code generates the following markup:

<a href="moreinfo.php?firstName=Tom&age=3"> Find out more info on this person </a>  </p>

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

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

Note that the ampersand (&) character needs to be encoded as &amp; inside XHTML markup.

URL encoding

PHP gives you a function called urlencode() that can encode any string using URL encoding.

Demo

<?php
$firstName ="Tom" ;
$homePage ="http://www.example.com/" ;
$favoriteSport ="PHP coding" ;
$queryString ="firstName=". urlencode($firstName)." &amp;homePage=".urlencode($homePage)." & amp;favoriteSport=". urlencode($favoriteSport);
echo'<p>  <a href="moreinfo.php?'. $queryString.'"> Find out more info onthis person </a>  </p>';
?>/*www.  j a  va2 s.c  o  m*/

Result

PHP can create a query string from array using 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.

Demo

<?php

$fields = array (
"firstName" => "Tom" ,
"homePage" => " http://www.example.com/" ,
"favoriteSport" => "coding");  
echo'<p>  <a href="moreinfo.php?'. htmlspecialchars(http_build_query($fields)).'"> Find out more info on this person </a>  </p>';
?>// w  w  w .  jav a 2 s . co m

Result

Related Topic