Solved

PHP Passing Variables

Posted on 2010-11-09
14
598 Views
Last Modified: 2012-05-10
Hi everybody! I'm stuck on what seems to be a simple project. I'm supposed to create a "Movies" class that determines the cost of a movie ticket to a cinema, based on the move goer's age. The cost of a full price ticket is $10. I'm supposed to assign the age to a private data member. I'm supposed to use a public member function to determine the ticket price, based on the following schedule:

Under 5 = $0
5 to 7 = $5
18 to 55 = $10
Over 55 = $8

I am required to do all of this with the following files:

   1. Movies.html
   2. Admission.php
   3. Movies.php

I did my best to code most of this on my own because I really want to learn. However I have NO idea how to pass the variables from Admissions.php to Movies.php and then back to Admissions.php to display the ticket price.

Many thanks in advance for the help!

Below is the code I have so far:  
<!--Movies.php-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Movies</title>
<meta http-equiv="Content-Type"
	content="text/html; charset=iso-8859-1" />
</head>
<body>
<?php

	class Movies
	{
		private $age = 0;
		private $ticketPrice = 10.00;
		
		public function Movies($age){
		$this->age = $age;
		}

		public function Movies($ticketPrice){
			
			if(age < 5){
			$this->ticketPrice = 0;
			echo"<p>The ticket price is $ticketPrice </p>\n";
			}
			else{
				if(age > 5 && age < 18){
				$this->ticketPrice = $ticketPrice / 2;
				echo"<p>The ticket price is $ticketPrice </p>\n";
				}
			
			else{
				if(age >= 18 && age <= 55){
				$this->ticketPrice = $ticketPrice;
				echo"<p>The ticket price is $ticketPrice </p>\n";
				}
			
			else{
				if(age > 55 ){
				$this->ticketPrice = $ticketPrice - 2.00;
				echo"<p>The ticket price is $ticketPrice </p>\n";
				}
			
			else
				echo"<p>error</p>\n";
			}
		}
	 }
  }
}
?>
</body>
</html>

Open in new window

<!--Movies.html-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Movies</title>
<meta http-equiv="Content-Type"
	content="text/html; charset=iso-8859-1" />
</head>
<body>
<h1>Welcome to the movies!</h1>

<p>Enter your age to determine your price.</p>

<form method="post" action="Admission.php"> 
<p>Age <input type="text" name="age" /></p>
<p><input type="submit" value="Submit" /></p>
</form>

</body>
</html>

Open in new window

<!--Admissions.php-->
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title>Movies</title>
<meta http-equiv="Content-Type"
	content="text/html; charset=iso-8859-1" />
</head>
<body>

<?php

$age = $_POST["age"]; //Get age from Movies.html ?????

require_once(Movies.php);

$ticketPrice = new Movies(); //Get ticketPrice from Movies.php ?????

echo"<p>Your ticket price is $ticketPrice. </p>";

?>
</body>
</html>

Open in new window

0
Comment
Question by:dvcrdu
14 Comments
 
LVL 10

Expert Comment

by:Tyler Laczko
ID: 34097990
very simple. anything in a form can be accessed on the next page by using - $_GET or $_POST

if your case you are using <form method='post'>
so you need to use $_POST


EG
<form method="post" action="Admission.php">
<p>Age <input type="text" name="age" /></p>
<p><input type="submit" value="Submit" /></p>
</form>

on Admission.php if you use $_POST['age'] it will give you the age.

add
<?php echo  $_POST['age']; ?> to your admission.php page and you will see what i mean.





if you change your form method='post' to method='get' you will see your data in the url

eg
admission.php?age=10

0
 
LVL 10

Expert Comment

by:TRW-Consulting
ID: 34099456
You could also use $_SESSION variables:

   session_start();
   code ... code ....
   $_SESSION['age'] = $age;

Then in your other scripts just use:

   session_start();
   $age = $_SESSION['age'];


But that's not the main reason I am putting a comment here. I was wondering what the price is for ages 8 to 17  :-)
0
 

Author Comment

by:dvcrdu
ID: 34102181
professionalcomputersolutions, thanks for your reply. I would like to just stick with POST for this project. Could you elaborate further on where exactly I should put your recommended code? Also is there anything else that you can see that I need to change? Thank you so much!

TRW-Consulting: also thank you for your reply, I'm not very familiar with session at this point which is why I'm just using POST. Ages 5 to 7 = $5 was a typo. It was meant to be: 5 to 17 = $5.

Thanks guys for your help!
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34102218
Is this a homework assignment by any chance?  We are prohibited by the TOS of Experts Exchange from working on those in anything more than general terms.

This shows the complete moving parts, all in one simple script which is the way the pros would do this.  You might want to add some sanity checks about the input values, like making sure they are numbers.
<?php // RAY_temp_movies.php

error_reporting(E_ALL);



// FROM THE POST AT EE

/*

Under 5 = $0

5 to 7 = $5  // ASSUME THIS IS A TYPO - S/B 17

18 to 55 = $10

Over 55 = $8

*/



// IF ANYTHING IS IN THE URL OR THE FORM INPUT

if (!empty($_GET["age"]))

{

    if   ($_GET["age"] <  5)                          $price =  0;

    if ( ($_GET["age"] >  5) && ($_GET["age"] < 17) ) $price =  5;

    if ( ($_GET["age"] > 17) && ($_GET["age"] < 55) ) $price = 10;

    if   ($_GET["age"] > 55)                          $price =  8;



    echo PHP_EOL . "BECAUSE YOU ARE {$_GET["age"]} YEARS OLD, YOUR PRICE IS \$$price";

}

// END OF PHP - PUT UP THE FORM

?>

<form>

YOUR AGE: <input name="age" />

<input type="submit" value="GET MY MOVIE TICKET PRICE" />

</form>

Open in new window

0
 

Author Comment

by:dvcrdu
ID: 34106408
Thanks for your help Ray Paseur! No this is not an official homework assignment. I am learning this on my own out of a book. I do appreciate you showing me how this works on one file but I am trying to put all this together in the 3 above files for the sake of learning how to pass variables from one document to the other. Could you please direct me on how to modify the code I posted so that It will work? I am really anxious to see this work. Thanks again, I really do appreciate the help so far!
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34106606
The PHP.net web site has some good introductory material on it.  This covers the use of forms.
http://us3.php.net/manual/en/tutorial.forms.php

In a nutshell, there are two commonly used types of forms - GET and POST.  GET sends the arguments in the URL.  Post sends the arguments in the POST string.  PHP interprets these values into $_GET and $_POST respectively before your script gets control.  These are superglobal arrays - available in all namespaces and variable scopes.  You can use var_dump() to print them out when you are debugging.

I cannot think of any reason to use three scripts - why would you want to do that?
0
 

Author Comment

by:dvcrdu
ID: 34108445
It's not what I want to do, it's what the book has me doing and I would like to learn it. Thank you.
0
Why You Should Analyze Threat Actor TTPs

After years of analyzing threat actor behavior, it’s become clear that at any given time there are specific tactics, techniques, and procedures (TTPs) that are particularly prevalent. By analyzing and understanding these TTPs, you can dramatically enhance your security program.

 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34111531
The question is completely answered at ID:34106606.  That is how you pass variables from one document to the other.  If you want to lbranch out, you can learn about Sessions and Cookies, but my sense is that you would benefit from a building-block approach at this point in your studies.  So master GET and POST for now.

Not sure I see the wisdom of that book, whatever it is.  I have about eleven shelf feet of books on PHP and MySQL and I have read them all.  My advice is to learn a little more about how HTTP works, and the principles of computer science, and human work patterns.  Then you will see that one script is a good idea and three scripts are a bad idea.

Here is why:

Each HTTP request from a client to a server results in a single, atomic and complete response from the server.  Look up the term "RESTful" in the Wikipedia to learn more.  A script can be aware of its environment, including the date and time, the server configuration, the contents of a data model, and the variables passed to it in the GET and POST arrays.  Based on all of these factors the script will create a response, probably HTML, and send that response to the browser.  As these factors are varied, one script can create different responses -- in essence it creates different web pages, depending on what it finds in its environment and its passed variables.  If you want (for example) three web pages that present different view of your data - maybe one shows baseball products, one shows basketball shoes and one shows football uniforms - you don't write three scripts.  You write one script, a "generalized solution" and you let the external factors, like the GET array, drive the general solution to appropriate output.

In computing, there is a concept called "Model-View-Controller" which describes the division of labor between the three important elements of client-server systems.  The Model is the underlying data, usually a data base.  In your case, the Model is the knowledge of what age gets what ticket price.  The View is the presentation of the knowledge - in your case it is the echo that tells the ticket price.  The Controller is the collected ways that clients signal the script to influence its output.  In your case, the Controller is the HTML form input asking the client to enter her age.  If you design your applications correctly, you will have minimal points of intersection among these three components, and in particular, the View will be easy to modify without any changes needed in the other two components.  As written above, all three of your scripts create browser output - almost certainly not what you want.

When you are working alone on a learning exercise, it is not hard to remember where you put all the code and variables.  When you begin working on any project of importance, you will be working with others and organization will quickly become your biggest issue.  You will want version control.  You will want code and variable encapsulation (you've got some encapsulation in the use of the Movies class).  And you will want to know where you put everything.  If you have a single script that handles a task, you will have 2/3 fewer places you need to control and organize!

I am a fan of "frameworks" and you might consider isolating the Movies class into its own script.  Then you could use include() to bring it into the other scripts.  Since you are dealing with external data, you will need to filter and validate that data before you use it in your code.  You might also put your filtering algorithms into the same commonly-shared script with the Movies class.  This way, as you add more functionality to your site, the common elements can be written once, tested thoroughly and stored away where they are safe.  Just a thought.  

Best regards, ~Ray

0
 

Author Comment

by:dvcrdu
ID: 34115544
Thank you for your insight. I really do appreciate your help and I value your expert opinion. However the question has not been completely answered. Is there a solution to fix the code I posted so that I will function the way I need it to? If so, please tell me and I'll close the question. Thanks again.
0
 
LVL 108

Accepted Solution

by:
Ray Paseur earned 500 total points
ID: 34116155
The question IS completely answered at ID:34106606.  Read the online man pages!  Fixing the code you posted is the wrong way to design the application.  That's like asking, "but can't I drive screws with a hammer?"  You can try but the results may be suboptimal.

One of the many reasons why: You have three different scripts and that means you have 3 times as much chance for error.

You might find some of these search results helpful:
http://lmgtfy.com?q=Object+Oriented+Programming+in+PHP

Here are your three scripts.  First, the Class script.
<?php // RAY_temp_dvcrdu_Classes.php

error_reporting(E_ALL);



class Movies

{

    protected $ticketPrice;



    public function __construct()

    {

        $this->ticketPrice = 10.00;

    }



    public function getTicketPrice($age)

    {

        // PESSIMISTIC FILTERING

        if (!is_numeric($age)) return FALSE;

        if ($age < 0)          return FALSE;



        // TEST AGE RANGES

        if  ($age <  6)                  { $t = 0.0; }

        if( ($age >  5) && ($age < 18) ) { $t = $this->ticketPrice / 2.0; }

        if( ($age > 17) && ($age < 56) ) { $t = $this->ticketPrice; }

        if  ($age > 55)                  { $t = $this->ticketPrice - 2.00; }



        // IF A PRICE WAS SET

        return number_format($t,2);

    }

}

Open in new window

0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 500 total points
ID: 34116159
Next the form script.
<?php // RAY_temp_dvcrdu_Movies.php ?>

<!--Movies.html-->

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd" />

<html xmlns="http://www.w3.org/1999/xhtml">

<head>

<title>Movies</title>

<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />

</head>

<body>

<h1>Welcome to the movies!</h1>



<p>Enter your age to determine your price.</p>



<form method="post" action="RAY_temp_dvcrdu_Admissions.php">

<p>Age <input type="text" name="age" /></p>

<p><input type="submit" value="Submit" /></p>

</form>



</body>

</html>

Open in new window

0
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 500 total points
ID: 34116162
Finally the action script.
<?php // RAY_temp_dvcrdu_Admissions.php

error_reporting(E_ALL);



// FILTER INPUT AND SET DEFAULT TO ERROR

$age = (is_numeric($_POST["age"])) ? $_POST["age"] : '-1';



// LOAD AND INSTATIATE THE CLASS

require_once("RAY_temp_dvcrdu_Classes.php");

$obj = new Movies;



// CALL FOR THE PRICE

$tkt = $obj->getTicketPrice($age);

if ($tkt)

{

    echo"<p>Because you are $age years old, your ticket price is \$$tkt. </p>" . PHP_EOL;

}

// HANDLE ERROR

else

{

    echo"<p>Data in '{$_POST["age"]}' is unusable, sorry. </p>" . PHP_EOL;

}



// MAKE IT EASIER TO TEST

?>

<a href="RAY_temp_dvcrdu_Movies.php">Try Again</a>

Open in new window

0
 

Author Closing Comment

by:dvcrdu
ID: 34116908
Thank you Mr. Paseur! I just wanted to follow what my book has me doing. Again, I'm teaching myself and really appreciate the help getting me through this. I wish I had a teacher like you to visit when I'm stuck. Thanks again.
0
 
LVL 108

Expert Comment

by:Ray Paseur
ID: 34117832
Any time you post a question here at EE I will be glad to help, and there are lots of experts here who are great teachers.  You might find this book valuable (I did - it has been in my professional library since its first printing):
http://www.sitepoint.com/books/phpmysql4/

Thanks for the points and happy learning! ~Ray
0

Featured Post

How to improve team productivity

Quip adds documents, spreadsheets, and tasklists to your Slack experience
- Elevate ideas to Quip docs
- Share Quip docs in Slack
- Get notified of changes to your docs
- Available on iOS/Android/Desktop/Web
- Online/Offline

Join & Write a Comment

Author Note: Since this E-E article was originally written, years ago, formal testing has come into common use in the world of PHP.  PHPUnit (http://en.wikipedia.org/wiki/PHPUnit) and similar technologies have enjoyed wide adoption, making it possib…
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
Learn how to match and substitute tagged data using PHP regular expressions. Demonstrated on Windows 7, but also applies to other operating systems. Demonstrated technique applies to PHP (all versions) and Firefox, but very similar techniques will w…
The viewer will learn how to count occurrences of each item in an array.

707 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

20 Experts available now in Live!

Get 1:1 Help Now