[2 days left] What’s wrong with your cloud strategy? Learn why multicloud solutions matter with Nimble Storage.Register Now

x
?
Solved

PHP Passing Variables

Posted on 2010-11-09
14
Medium Priority
?
678 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
VIDEO: THE CONCERTO CLOUD FOR HEALTHCARE

Modern healthcare requires a modern cloud. View this brief video to understand how the Concerto Cloud for Healthcare can help your organization.

 
LVL 111

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 111

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
 
LVL 111

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 111

Accepted Solution

by:
Ray Paseur earned 2000 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 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 2000 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 111

Assisted Solution

by:Ray Paseur
Ray Paseur earned 2000 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 111

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

New feature and membership benefit!

New feature! Upgrade and increase expert visibility of your issues with Priority Questions.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Developers of all skill levels should learn to use current best practices when developing websites. However many developers, new and old, fall into the trap of using deprecated features because this is what so many tutorials and books tell them to u…
This article discusses how to implement server side field validation and display customized error messages to the client.
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.
The viewer will learn how to create a basic form using some HTML5 and PHP for later processing. Set up your basic HTML file. Open your form tag and set the method and action attributes.: (CODE) Set up your first few inputs one for the name and …
Suggested Courses

649 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