回声不显示我的结果/答案

时间:2016-10-28 09:01:50

标签: php lamp php-7

我正在使用php 7.0,apache2,mysql ver 14.14发行版5.6.17和phpmyadmin 5.7

由于某种原因,我的php文件不会显示变量$ result的值。每当我尝试使用“echo”时它就不会显示它。甚至不是另一个变量(总和)。

我的html文件包含以下代码:

<!doctype html>
<html lang="en-us">
<head>
<title>calculation form</title>
<meta charset="utf-8">
</head>


<body>

<form method="post" action="calculate.php">
<p>Value 1: <input type="text" name="val1" size="10"></p>
<p>Value 2: <input type="text" name="val2" size="10"></p>
<p>Calculation:<br>
<input type="radio" name="calc" value="add"> add<br>
<input type="radio" name="calc" value="subtract"> subtract<br>
<input type="radio" name="calc" value="multiply"> multiply<br>
<input type="radio" name="calc" value="divide"> divide
</p>
<p><input type="submit" name="submit" value="Calculate"></p>
</form>
</body>
</html> 

我的php代码包含以下内容:

<?php

$sum = 0;

if(($_POST[val1] == "") || ($_POST[val2] == "") || ($_POST[calc] == ""))
{
    header("Location: calculate_form.html");
    exit;
}

if($_POST[calc] == "add")
{
    $result = $_POST[val1] + $_POST[val2];
}

if($_POST[calc] == "subtract")
{
    $result = $_POST[val1] - $_POST[val2];
}

if($_POST[calc] == "multiply")
{
    $result = $_POST[val1] - $_POST[val2];
}

if ($_POST[calc] == "divide") {
    $result = $_POST[val1] / $_POST[val2];
}

?>



<?php

echo $result;
echo $sum;

?>

1 个答案:

答案 0 :(得分:0)

你必须在条件内回应,否则你必须全局设置变量

<?php

    $sum = 0;

    if(($_POST['val1'] == "") || ($_POST['val2'] == "") || ($_POST['calc'] == ""))
    {
        header("Location: calculate_form.html");
        exit;
    }

    if($_POST['calc'] == "add")
    {
        $result = $_POST['val1'] + $_POST['val2'];
        echo $result;
    }

    if($_POST['calc'] == "subtract")
    {
        $result = $_POST['val1'] - $_POST['val2'];
        echo $result;
    }

    if($_POST['calc'] == "multiply")
    {
        $result = $_POST['val1'] - $_POST['val2'];
        echo $result;
    }

    if ($_POST['calc'] == "divide") {
        $result = $_POST['val1'] / $_POST['val2'];
        echo $result;
    }

    ?>

或者像这样设置

 if($_POST[calc] == "add")
    {
        $result = $_POST[val1] + $_POST[val2];
        $sum= $result;
    }

yuo $_POST[val1]

也有错误

应为$_POST['val1']

更新了示例

<?php

    $sum = 0;
$_POST['val1']=5;
$_POST['val2']=10;
$_POST['calc']='add';
    if(($_POST['val1'] == "") || ($_POST['val2'] == "") || ($_POST['calc'] == ""))
    {
        header("Location: calculate_form.html");
        exit;
    }

    if($_POST['calc'] == "add")
    {
       $sum = $_POST['val1'] + $_POST['val2'];

    }

    if($_POST['calc'] == "subtract")
    {
      $sum = $_POST['val1'] - $_POST['val2'];

    }

    if($_POST['calc'] == "multiply")
    {
      $sum = $_POST['val1'] - $_POST['val2'];

    }

    if ($_POST['calc'] == "divide") {
       $sum = $_POST['val1'] / $_POST['val2'];

    }
echo $sum;
    ?>