Echo 不显示我的 result/answer

Echo not displaying my result/answer

我正在使用 php 7.0、apache2、mysql ver 14.14 distribution 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;

?>

你必须在 if 条件下回显或者你必须全局设置变量

<?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;
    }

你也有错误 $_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;
    ?>