douji0073 2014-11-29 20:06
浏览 78
已采纳

if elseif php简单的计算器

This is form for calculator

<form method='post' action='result.php' name='calc_form'>

<input type='text' name='input1' size='15'>

<select name='operation'>
<option value="plus">+</option>
<option value="minus">-</option>
<option value="multi">*</option>
<option value="invalid">**</option>
<option value="divide">/</option>
</select>  

<input type='text' name='input2' size='15'>
<input type='submit' value='go'>


</form> 

This is php with if elseif statement

<?php

define ('INVALID_INPUT', 'ERROR: invalid input');
define ('INVALID_OPERATOR', 'ERROR: invalid operator');


$result = null;

if 
(isset($_POST) and 
isset($_POST['input1']) and 
isset($_POST['input2']) and 
isset($_POST['operation']))
  {
  $input1 = $_POST['input1'];   
  $input2 = $_POST['input2'];
  $operation = $_POST['operation'];
     switch ($operation)
       {
       case 'plus':
         $result = $input1 + $input2;
         break;
       case 'minus':
         $result = $input1 - $input2;
         break;
       case 'multi':
         $result = $input1 * $input2;
         break;
       case 'divide':
         $result = $input1 / $input2;
         break;
       default: 
         $result = INVALID_OPERATOR;           
         break;
       }
    }  
elseif
(!isset($_POST) and 
isset($_POST['input1']) and 
isset($_POST['input2']) and 
isset($_POST['operation']))
{  
$result = INVALID_INPUT;
}

if ($result !== null)
{
echo <<<EOM


<h2>you calculate</h2> $input1 

<h2>and</h2>  $input2 

<h2>result is:</h2>

$result

EOM;
 }

?>

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?

  • 写回答

3条回答 默认 最新

  • douwen1213 2014-11-29 21:18
    关注

    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']))
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 chaquopy python 安卓
  • ¥50 Kubernetes&Fission&Eleasticsearch
  • ¥15 CSS实现渐隐虚线框
  • ¥15 有没有帮写代码做实验仿真的
  • ¥15 報錯:Person is not mapped,如何解決?
  • ¥30 vmware exsi重置后登不上
  • ¥15 易盾点选的cb参数怎么解啊
  • ¥15 MATLAB运行显示错误,如何解决?
  • ¥15 c++头文件不能识别CDialog
  • ¥15 Excel发现不可读取的内容