Jump to content

PHP Newbie - Forms


JulianHarford

Recommended Posts

Hi all,

 

I've been learning PHP since the beginning of this year. I am self-taught -- I have not received any formal training in programming. I understand some of the basics, but I felt I could do more than just a "Hello World" right now. :P

 

Anyway, I decided to create a fake app to help improve my PHP knowledge. It's quite simple. Users visit a page that asks them for a choice, then leads them to a form. Ultimately, I'd end up storing the info they provide in a database. I haven't jumped on the database part yet, because I'd like someone experienced to take a look at what I have so far and offer any helpful tips.

 

Currently I have three files in the /cars/ directory: index.html, cars.php, form.php. I figured I'd need one to ask what the customer wants, another that would show a generic form, and the last containing specific forms which would show up based on the choice selected.

 

index.html:

 

<!DOCTYPE html>
<html>
   <head>
       <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
       <title>Select car</title>
   </head>
   <body>
       <form action="cars.php" method="POST">
           Select the required car(s):<br />
           <input type="radio" name="car" value="ford" />Ford <br />
           <input type="radio" name="car" value="honda" />Honda <br />
           <input type="radio" name="car" value="both" />Both <br />
           <input type="submit" name="submit" value="Continue" /> <br />        
       </form>
   </body>
</html>

 

cars.php:

 

<?php
include('form.php');
// Generic form in HEREDOC
$cars = <<<FORM
   Color:
   <select name="color">
       <option value="black">Black</option>
       <option value="blue">Blue</option>
       <option value="red">Red</option>
       <option value="green">Green</option>
       <option value="yellow">Yellow</option>
       <option value="pink">Pink</option>
       <option value="orange">Orange</option>
       <option value="white">White</option>
   </select>
   <br />
   Insurance Company:
   <input type="text" name="insurance" size="20" />
   <br />
   Insurance Phone No.:
   <input type="text" name="insurancephone" size="20" />
   <br />
   No. of drivers:
   <input type="text" name="drivers" size="5" />
   <br />
   Lease duration (in hours):
   <input type="text" name="lease" size="5" maxlength="2" />
   <br />
   Comments:<br />
   <textarea name="comments" rows="3" cols="40"></textarea>
FORM;


// Check to see if an option was selected before hitting Submit
if (isset($_REQUEST['submit'])) {
   $car = $_REQUEST['car'];

   // If customer wants both cars
   if ($car == 'both') { 
       echo 'Your cars will be added under the same list.<br />';
       echo $formFord;
       echo $formHonda;
   }
   else if ($car == 'honda') {
       echo 'Ford choice:<input type="text" name="choiceFord" size=10" /><br />';
       echo $formFord; 
   }
   else {
       echo 'Honda choice:<input type="text" name="choiceHonda" size=10" /><br />';
       echo $formHonda; 
   }
   echo $cars;
}
else {
   echo 'Please go back and choose an option.';
}
?>

 

form.php:

 

<?php
$formFord = <<<FORD
   Cylinders:
   <select name="cylinder">
       <option value="four">4 cylinder</option>
       <option value="six">6 cylinder</option>
       <option value="eight">8 cylinder</option>
       <option value="teh">10 cylinder</option>
       <option value="twelve">12 cylinder</option>
   </select>
   <br />
FORD;


$formHonda = <<<HONDA
   Looking to save?
   <input type="radio" name="power" value="yes" />Yes
   <input type="radio" name="power" value="no" />No
   <br />
   Features:<br />
   <input type="radio" name="feature" value="all" />All<br />
   <input type="radio" name="feature" value="standard" />Standard<br />
   <input type="radio" name="feature" value="other" />Custom:<br />
       <input type="checkbox" name="custom" value="airbag" />Air bags
       <input type="checkbox" name="custom" value="remote" />Remote lock
       <input type="checkbox" name="custom" value="sunroof" />Sunroof<br />
       <input type="checkbox" name="custom" value="navi" />Navigation system
       <input type="checkbox" name="custom" value="bluetooth" />Bluetooth
       <input type="checkbox" name="custom" value="xmradio" />XM Radio<br />
       <input type="checkbox" name="custom" value="foglight" />Foglights
HONDA;
?>

 

That is what I have so far, and it currently does what I want it to do. But as you've already noticed, it's not very well-thought out (at least I don't feel like it is). I'm sure there are better ways to accomplish what I put above. Just need some constructive criticism before I keep going any further. On that note, if you feel like I should keep going before I can receive any criticism, I won't mind.

 

Thanks in advance for any help!

Link to comment
Share on other sites

Everybody has to start somewhere and as you said the above certainly does the job. That said, writing a script which performs a task is only half of the job. Other questions you need to ask are: what if I needed to change my code? Would it be easy to do? Another important one is am I duplicating code? Or can the script be structured in a way in which commonly used logic/functionality? The answer to all of these questions is objects.

 

Consider this:

 

//function to work out bhp
function calculateBhp( $engineSize ){

//logic for working out bhp
return 90;

}
//define our car
$car = array( 'make' => 'honda', 'engineSize' => 1.4, 'doors' => 3 );
//echo out to the user
echo $car['make'];
echo $car['engineSize'];
echo calculateBhp( $car['engineSize'] );
... 

 

Cool, so we have a function that works out engine size and we print a few array elements to the user. That's fine, but what if we wanted to use that function in another file? It'd have to be included in. Also, what if certain manufacturers used different values to work out bhp? Then we'd have to have multiple functions which all applied different calculations... this is when code would start to get hard to manage. Here's the same functionality but ported to OO:

 

class Car{
public $make;
public $engineSize;
public $doors;
public function calculateBhp(){
 //logic to work out bhp
 return 90;
}
public function getMake(){
 return $this->make;
}
}
class Honda extends Car{
public $make = 'honda'
public function calculateBhp(){
 //different logic to work out bhp
 return 100;
}
public function getMake(){
 //here we're calling the method in Car which will return Honda
 $str = parent::getMake();
               //now we're just appending a space then the engine size
 return $str . ' ' . $this->engineSize;
}
}
class Ford extends Car{
public $make = 'ford';

}
//now we have our classes defined lets get some instances
$honda = new Honda();
$honda->engineSize = 1.4;
$ford = new Ford();
$ford->engineSize = 1.2;
echo $honda->getMake(); //returns honda 1.4
echo $honda->calculateBhp(); //returns 100
echo $ford->getMake(); //returns ford because unlike the Honda class there is no override in the Ford class
echo $ford->calculateBhp(); //returns 90

 

As you can see code is becoming separated out, therefore, any changes that need to be made which as specific to a manufacturer it'd be easy to implement new methods or override existsing ones.

 

Any questions then give me a shout :P Happy learning

 

One thing I noticed is on your else if you're checking if the string stored within $car is "honda" but you're displaying the ford form.

Link to comment
Share on other sites

Thanks for explaining, exeTrix! You're right -- I do need to ask myself questions like the ones you mentioned in your post. I've read up a bit on classes/functions, but still trying to get it all in my head.

 

I am slightly confused about the calculateBhp() in your code. From what I understand, the car class defines the attributes of the car. Then you proceed to create "Honda" and "Ford" with that class. So why are you re-creating calculateBhp() those two classes? Wouldn't the logic be the same regardless? Or maybe they need different names?

 

Just trying to absorb classes and functions since I'm quite sure I'll be using both a lot. Thanks for pointing out the form display error, by the way. :P

Link to comment
Share on other sites

That's not a problem and don't worry OO will come in time. I remember when I was trying to get my head around it nightmare but so useful when I did!

 

The reason behind calculateBhp being defined twice is just to illustrate inheritance. Lets say that all manufacturers calculate BHP in the same way, however, Honda use a slightly different calculation for their cars. So rather than making a new method with a different name we just override the functionality in our child class. Inheritance is about sharing common application logic with child classes. Moreover, having the same method name means that you don't have to know which manufacturer you're dealing with in order to call the different method names. In the case of the example above it's very simple and doesn't really show object being generated dynamically.

 

If we were getting the manufacturers from a database result set then you can see it a little more clearly:

 

<?php


//this is our fake result set
$cars = array( 0 => array( 'make' => 'Honda' ), 1 => array( 'make' => 'Ford' ) );


class Car{
public $make;
public $engineSize;
public $doors;

public function calculateBhp(){
 return 90;
}


public function getMake(){
 return $this->make;
}
}


class Honda extends Car{
public $make = 'honda';


public function calculateBhp(){
//different logic to work out bhp
  return 100;
}


public function getMake(){
  //here we're calling the method in Car which will return Honda
  $str = parent::getMake();
                                //now we're just appending a space then the engine size
  return $str . ' ' . $this->engineSize;
}
}


class Ford extends Car{
public $make = 'ford';
}
//now we spin over the $cars array
foreach( $cars as $car ){
//now we don't know what the manufacturer is, we could put some if statements in but that'd be lame
//alternative? do this
$make = $car['make'];


$carObj = new $make;


echo $carObj->getMake() . "<br />";
echo $carObj->calculateBhp() . "bhp<br />";


} 

 

That should return the following:

honda 1.4

100bhp

ford

90bhp

 

As you can see the same method has been called on both objects but you get different results. Inheritance is extremely powerful, and I use it constantly in my day job to share code between different objects.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.