Monday, 27 July 2015

Passing variable in a URL - PHP Tutorial 10


Passing variables in a URL

When you work with PHP, you often need to pass variables from one page to another. This lesson is about passing variables in a URL.

How does it work?

Maybe you have wondered why some of the URLs of some websites look something like this:
 http://awebsite.com/page.php?id=123
 
 
Why is there a question mark after the page name?
The answer is that the characters after the question mark are an HTTP query string. An HTTP query string can contain both variables and their values. In the example above, the HTTP query string contains a variable named "id", with the value "123".
Here is another example:

 http://awebsite.com/page.php?name=Johnny
 
 
Again, you have a variable ("name") with a value ("Johnny").

How to get the variable with PHP?

Let's say you have a PHP page named people.php. Now you can call this page using the following URL:

 people.php?name=Johnny
 
 
With PHP, you will be able to get the value of the variable 'name' like this:

 $_GET["name"]
 
 
So, you use documentation$_GET to find the value of a named variable. Let's try it in an example:

 <html>
 <head>
 <title>Query string</title>
 </head>
 <body>

 <?php

 // The value of the variable name is found
 echo "<h1>Hello " . $_GET["name"] . "</h1>";

 ?>
    
 </body>
 </html>
 
 

Several variables in the same URL

You are not limited to pass only one variable in a URL. By separating the variables with &, multiple variables can be passed:

 people.php?name=Johnny&age=21
 
 
This URL contains two variables: name and age. In the same way as above, you can get the variables like this:

 $_GET["name"]
 $_GET["age"]
 
 
Let's add the extra variable to the example:

 <html>
 <head>
 <title>Query string </title>
 </head>
 <body>

 <?php

 // The value of the variable name is found
 echo "<h1>Hello " . $_GET["name"] . "</h1>";
  
 // The value of the variable age is found
 echo "<h1>You are " . $_GET["age"] . " years old </h1>";

 ?>

 </body>
 </html>
 
 
Now you have learned one way to pass values between pages by using the URL. In the next lesson, we'll look at another method: forms.

Written by

is one of the Team Member of Programmer vs Hacker. He has written many articles on this website and is a patner of this website.

0 comments:

Post a Comment

We’re eager to see your comment. However, Please Keep in mind that comments are moderated manually by our human reviewers according to our comment policy, and all the links are nofollow. Using Keywords in the name field area is forbidden. Let’s enjoy a personal and evocative conversation.

© 2015 Programmer vs Hacker. All rights resevered.