简体   繁体   中英

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

This Html coding with css and php.I am getting an error that you result variable is not declareed.but i had declare it in my form.please check and tell me about this error. calculator

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>

This is Php coding

if(isset($_POST['add'])){
    $first_value = $_POST['f_value'];
    $sec_value = $_POST['s_value'];

    //--calculation variables---//

         $result = $first_value + $sec_value;           


        }
        ?>  

    </head>

Html form starts from here

<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= '';
}

Your $result is falling out of scope:

<?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' >

To solve this problem, first declare $result within the same scope as you intend to echo it:

<?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' >

Futher information about variable scope

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM