我得到错误的Html形式,而给予值为php代码


I am getting error in Html form while giving a value as php code

使用css和php编写的Html代码。我得到一个错误,你的结果变量没有声明。但我必须在表格上申报。请检查并告诉我这个错误。计算器

this style .css file

        <style>
        form {
    display:block; 
    background-color: #333399;
    width:300px;
    height:500px;
    border:thick;
    border: #330000;
    color: #FFCC00;
    }

h1 {
    text-align:center;
    z-index: 2px;
    }
    </style>

这是Php代码

if(isset($_POST['add'])){
    $first_value = $_POST['f_value'];
    $sec_value = $_POST['s_value'];
    //--calculation variables---//
         $result = $first_value + $sec_value;           

        }
        ?>  
    </head>

Html表单从这里开始

<body>
        <form  method="post" action="new.php" name="calculator">
    &nbsp;<h1> calculator</h1> 
    <p>
    <strong>Frsit value</strong>&nbsp;&nbsp;&nbsp;&nbsp;
    <input  type="text" name="f_value" >
    <p><strong>Second value</strong> <input type="text" name="s_value" maxlength="50">
    <p>
    &nbsp;<input name="add" type="submit" value="add" >
    <!--&nbsp;<input name="sub" type="submit" value="sub">
    &nbsp;<input name="sub" type="submit" value="multiply">
    &nbsp;<input name="sub" type="submit" value="divide">-->
    `enter code here`<p>
    <h2 style="border:thick">Result
      <input type="text" maxlength="50" value="<?php echo $result ; ?>" Name='result' >
    </h2>

        </form>
</body>
</html>

此处使用isset

<input type="text" maxlength="50" value="<?php if(isset($result)) { echo $result; } ?>" Name='result' >
if(isset($_POST['add'])){
    $first_value = $_POST['f_value'];
    $sec_value = $_POST['s_value'];
    $result = $first_value + $sec_value;  
}
else{
    $result= '';
}

您的$result超出范围:

<?php
if(isset($_POST['add'])) {  //scope begins here
  //php omitted for brevity
  //$result is declared within this scope
  $result = $first_value + $sec_value;
} // scope ends here - after this point, $result no longer exists!
?>
<!-- html omitted for brevity -->
<!-- This is OUTSIDE the scope where $result was declared - we can't get it any more! -->
<input type="text" maxlength="50" value="<?php echo $result ; ?>" Name='result' >

要解决这个问题,首先在你打算回显它的同一作用域中声明$result:

<?php
$result = 0;
if(isset($_POST['add'])) {
  //php omitted for brevity
  //change $result's value
  $result = $first_value + $sec_value;
}
?>
<!-- html omitted for brevity -->
<input type="text" maxlength="50" value="<?php echo $result ; ?>" Name='result' >

关于变量作用域的详细信息