PDA

View Full Version : Can't see why this code doesn't work


BarneysPosse
11-28-2008, 07:53 AM
I've just been practicing with forms and php. I have this really simple form for a calculator:

<form method="get" action="script_practice.php">

Enter the First Number
<input type="text" name="number1">

Enter the Second Number <input type="text" name="number2">

Choose the operation
<input type="radio" name="op" value="add" checked>
Addition

<input type="radio" name="op" value="sub">
Subtraction

<input type="radio" name="op" value="mul">
Multiplication

<input type="radio" name="op" value="div">
Division <input type="submit" name="Submit" value="Submit">

</form>

and then the php script on script_practice.php:

<?php

if ( $op == "add" ) {
echo "$number1 + $number2 = ";
echo $number1 + $number2;
}

if ( $op == "sub" ) {
echo "$number1 - $number2 = ";
echo $number1 - $number2;
}

if ( $op == "mul" ) {
echo "$number1 * $number2 = ";
echo $number1 * $number2;
}

if ( $op == "div" ) {
echo "$number1 / $number2 = ";
echo $number1 / $number2;
}

?>


However it doesn't work. The script_practice.php loads without errors but the page is blank. I'm completely stumped as to why. :confused:

edbr
11-28-2008, 08:30 AM
your if statements are based on a value $op.
your form i would change method to post by the way will the pass a value $_POST['op'] you will need to declare then on script_practice.php:

[code]$op=$_POST['op'] ;
$number1=$_POST['number1'] ;
$number2=$_POST['number2'] ;

BarneysPosse
11-28-2008, 08:48 AM
Thanks edbr that did the trick. I was wondering how the variables in the php got their values from the form.

BarneysPosse
11-28-2008, 08:58 AM
Also,

would it be better to have the script this way?:


$op=$_POST['op'] ;
$number1=$_POST['number1'] ;
$number2=$_POST['number2'] ;

switch($op){
case "add":
echo "$number1 + $number2 = ";
echo $number1 + $number2;
break;
case "sub":
echo "$number1 - $number2 = ";
echo $number1 - $number2;
break;
case "mul":
echo "$number1 * $number2 = ";
echo $number1 * $number2;
break;
case "div":
echo "$number1 / $number2 = ";
echo $number1 / $number2;
break;
}
The research I've done so far seems to suggest that using switch statements are better than using if statements? I don't know I'm still wading through a bunch of information. Obvious beginner if you can't already tell.