如何将字段值设置为计算结果

时间:2015-06-18 06:06:29

标签: php html forms

我的表单有一个字段,其值来自php计算。计算只是涉及纯粹整数的基本算术。但有一种情况是价值为零。因此,该表格假定该字段已被清空。

我怎么能绕过那个? 这是一个代码示例。

if ( 
    isset($_POST['input1']) &&
    isset($_POST['input2']) &&
    isset($_POST['ans'])
    )
{   
    // CHECKING IF ANY OF THE FIELDS WERE LEFT EMPTY
    $input1 = $_POST['input1'];
    $input2 = $_POST['input2'];
    $ans = ($input1)-($input2);
    $ans_set = 0;

    if ($ans === $ans_set ) {
        # code...
        //echo "Same";
        $ans = '0';
    } else {
        # code...
        //echo "Different";
        echo "Check data types";
    }


    if ( 
        !empty($input1) &&
        !empty($input2) &&
        !empty($ans) 
         )
    {   
        $query = "INSERT INTO formaths VALUES ( 'NUll', NOW(),
                        '".mysql_real_escape_string($input1)."',
                        '".mysql_real_escape_string($input2)."',
                        '".mysql_real_escape_string($ans)."' )";

        $query_run = mysql_query($query);
                    if ( $query_run )
                    {
                        //header("Location:". __DIR__."../registration_success.php");
                        echo "<p class='echo'>Data entry was successful.</p>";
                    }
                    else
                    {
                        echo "<p class='echo'>It seems that we couldn't save that at this time.</p>";
                    }

    }
    else
    {
        echo "<p class='echo'>Please make sure all fields are filled and are correct.<br/>You must fill in the area field last!</p>";
    }
}

?>

<!DOCTYPE html>
<html>
<head>
    <title></title>
</head>
<body>
    <form action="formaths.php" method="POST">
        <input name="input1" type="text" autofocus/>
        <input name="input2" type="text"/>
        <input name="ans" type="text" value="<?php if (isset($ans)) { echo $ans; }?>" readonly />

        <input type="submit" value="DO IT" />
    </form>
    enter code here

</body>
</html>

0 个答案:

没有答案