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条)

报告相同问题?

悬赏问题

  • ¥30 自适应 LMS 算法实现 FIR 最佳维纳滤波器matlab方案
  • ¥15 lingo18勾选global solver求解使用的算法
  • ¥15 全部备份安卓app数据包括密码,可以复制到另一手机上运行
  • ¥15 Python3.5 相关代码写作
  • ¥20 测距传感器数据手册i2c
  • ¥15 RPA正常跑,cmd输入cookies跑不出来
  • ¥15 求帮我调试一下freefem代码
  • ¥15 matlab代码解决,怎么运行
  • ¥15 R语言Rstudio突然无法启动
  • ¥15 关于#matlab#的问题:提取2个图像的变量作为另外一个图像像元的移动量,计算新的位置创建新的图像并提取第二个图像的变量到新的图像