Passing Variables via the Query String - Exercise

Contact Us or call 1-877-932-8228
Passing Variables via the Query String - Exercise

Passing Variables via the Query String

Duration: 10 to 15 minutes.

In this exercise, you will write a script that says hello to different people based on what is passed through the query string.

  1. Open PhpBasics/Exercises/HelloWho.html in your editor. You will see that it is the same as the demo we looked at earlier.
  2. Modify HelloWho.html so that it has four links, each of which passes the name of one of the Beatles (Paul, John, George, and Ringo) to HelloWho.php, which is in the same directory.
  3. Open PhpBasics/Exercises/HelloWho.php in your editor. Modify the code so that it outputs a greeting based on the link clicked on HelloWho.html.
  4. Try it out in your browser.

Challenge

Change the links so that each Beatle gets a custom greeting (e.g, Howdy Paul, Hi John, Bye George, Hey Ringo).

Solution:

PhpBasics/Solutions/HelloWho.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Greeting the Beatles</title>
</head>
<body>
	Choose a Beatle to greet.
	<ul>
	<li><a href="HelloWho.php?Beatle=Paul">Paul</a></li>
	<li><a href="HelloWho.php?Beatle=John">John</a></li>
	<li><a href="HelloWho.php?Beatle=George">George</a></li>
	<li><a href="HelloWho.php?Beatle=Ringo">Ringo</a></li>
	</ul>
</body>
</html>

Solution:

PhpBasics/Solutions/HelloWho.php
<?php
	$beatle = $_GET['Beatle'];
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Hello <?php echo $beatle ?>!</title>
</head>
<body>
<?php
	echo "Hello $beatle!";
?>
</body>
</html>

Challenge Solution:

PhpBasics/Solutions/HelloWho-challenge.html
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title>Greeting the Beatles</title>
</head>
<body>
	Choose a Beatle to greet.
	<ul>
	<li><a href="HelloWho-challenge.php?Beatle=Paul&Greeting=Hi">Paul</a></li>
	<li><a href="HelloWho-challenge.php?Beatle=John&Greeting=Hello">John</a></li>
	<li><a href="HelloWho-challenge.php?Beatle=George&Greeting=Bye">George</a></li>
	<li><a href="HelloWho-challenge.php?Beatle=Ringo&Greeting=Hey">Ringo</a></li>
	</ul>
</body>
</html>

Challenge Solution:

PhpBasics/Solutions/HelloWho-challenge.php
<?php
	$beatle = $_GET['Beatle'];
	$greeting = $_GET['Greeting'];
?>
<!DOCTYPE HTML>
<html>
<head>
<meta charset="UTF-8">
<title><?= $greeting . ' ' . $beatle ?>!</title>
</head>
<body>
<?php
	echo "$greeting $beatle!";
?>
</body>
</html>
Next