Hướng dẫn php calculator if-else statement

This is form for calculator






+
-
*
**
/
  





 

This is php with if elseif statement

I even tried with only else statement and without condition but it wont show INVALID INPUT when nothing is added in form. What is wrong here?

asked Nov 29, 2014 at 20:06

The problem is with this piece of code:

if 
[isset[$_POST] and 
isset[$_POST['input1']] and 
isset[$_POST['input2']] and 
isset[$_POST['operation']]]

Even if a user enters nothing in the input fields, they will still pass isset[$_POST['input1']], since they are 'set' to an empty string. Try switching it to this instead:

if 
[isset[$_POST['input1']] && strlen[$_POST['input1']] &&
 isset[$_POST['input2']] && strlen[$_POST['input2']] &&
 isset[$_POST['operation']]]

answered Nov 29, 2014 at 21:18

CalCal

7,03724 silver badges28 bronze badges

1

You could just use an else statement instead of an else if statement. That way if you change the inputs you don't have to list each of them twice.

eg:

if [isset[$_POST] and 
isset[$_POST['input1']] and 
isset[$_POST['input2']] and 
isset[$_POST['operation']]] 
{
    // result = calculation
} else
{
    // result == code
}

Try this - I tested this on my server and it works!

calculator.php






    
    
    
    
    





 value="plus">+
 value="multi">*
 value="divide">/
  

Chủ Đề