Query string handling in PHP

Query strings

To access the data in a query string you can use the $_GET global array. Each element in this array has a key which is the name of the query string variable and a value which is the value of that variable.

<a href="mypage.php?variable1=value1&variable2=value2">my link</a>

This link loads the page mypage.php with two variables variable1 and variable2 with values value1 and value2 respectively.

echo $_GET['variable1'];
echo $_GET['variable2'];
// outputs:

Form data

The get method of forms sends the data to a page via a query string.

<form name="form1" id="form1" method="get" action="">
   <input name="textbox" id="textbox" type="text" value="value1" />
   <input name="textbox2" id="textbox2" type="text" value="value2" />
   <input type="submit" name="submitbutton" id="submitbutton" value="Submit" />

This form passes the value of the two text boxes to the page myform.php.

// outputs:
// Array (
//   [textbox] => value1
//   [textbox2] => value2
//   [submitbutton] => Submit
// )

echo $_GET['textbox'];
//outputs: value1

If the form is submitted with the default values the output is as above. All the data in the array is printed using the print_r function and the value of the text box is printed by getting the data directly from the array.



No tags