在同一页面的表单中提交并显示结果

I've a form in which I want the calculate function to be called and displayed on the same page. If there is an error, it should display in the span tag on the same page.

Here's what I have right now, and I'm running into problems:

index.php [UPDATED]:

<?php 

if (isset($_POST['submit'])) {
        $bdmm = $_POST['bdmm']; 
        $sdmm = $_POST['sdmm']; 



        $strings = array(
            $bdmm, 
            $sdmm, 
            $lgpm
        );

            if(!$bdmm){ 
                $error = "Error";
                exit();
            } 
            elseif(!$sdmm){ 
                $error = "Error";
                exit();
            } 


            //check whether the string is numeric
            foreach ($string as $string) {
                if (!preg_match("/^-?([0-9])+\.?([0-9])+$/", $string)) 
                { 
                    echo "Invalid entry. Please enter a number.";  
                } 
            }

                    $calc = new Calc();
            if (isset($bdmm)) {
                $calc->calculateMet($bdmm,$sdmm);
            }


}

// Defining the "calc" class 
class Calc { 
     private  $vs = 0; 
     private  $nob = 0;     
     private  $tw = 0; 


          public function calculateMet($b,$s)
          {  
                    //code to calculate

            //display nbnm  in textbox  
                    $nbnm = $nobr;

                      //display twkg in textbox    
                    $tw = $nob * 25;
                    $twr = round($tw);
                    $twkg = $tw;

                    exit; 
          } 

} 

?> 

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Calculator</title>
<link rel="stylesheet" type="text/css" href="main.css" />

</head>

<body>

   <!-- Begin Wrapper -->
   <div id="wrapper">


         <div id="column">
              <form id="deps" name="deps" action="<?php echo $_SERVER["PHP_SELF"]; ?>" method="POST"> 
                <?php
                     if (isset($_REQUEST['error'])){     
                        $err = $_REQUEST['error'];
                ?>
                <div id="er"> <span class="er" >&nbsp;<?php echo $err; ?></span></div>  
                <?php  } ?>
                <table class="table">
                    <tr>
                        <td class="field head">&nbsp;</td>
                        <td class="field cv"><label for="met">Metric</label></td>
                        <td class="field cv"><label for="eng">English</label></td>
                    </tr>
                    <tr>
                        <td class="field head"><label for="bd">Bore Dia.</label></td>
                        <td class="field"><input type="text" name="bdmm" id="bdmm" /><label for="bdmm">MM</label></td>

                    </tr>
                    <tr>
                        <td class="field head"><label for="sd">Screen Dia.</label></td>
                        <td class="field"><input type="text" name="sdmm" id="sdmm" /> <label for="sdmm">MM</label></td>

                    </tr>

                    <tr>
                        <td class="field head"><label for="nbn">No. of Bags needed</label></td>
                        <td class="field"><input type="text" name="nbnm" id="nbnm" value="<?php echo $nbnm; ?>" /></td>
                    </tr>
                    <tr>
                        <td class="field head"><label for="tw">Total Weight</label></td>
                        <td class="field"><input type="text" name="twkg" id="twkg" value="<?php echo $twkg; ?>" /> <label for="twkg">KG</label></td>

                    </tr>

                 </table>   
                        <input type="submit" id="submit" value="Calculate" />                
              </form>


         </div>

   </div>
   <!-- End Wrapper -->

</body>
</html>

There are mainly two things I want to show in the form:

1- If there is an error, it should display the error in the span tag -

<?php
                         if (isset($_REQUEST['error'])){     
                            $err = $_REQUEST['error'];
                    ?>
                    <div id="er"> <span class="er" >&nbsp;<?php echo $err; ?></span></div>  
                    <?php  } ?>

I did this^, but it does not throw any error even if the textbox is blank.

2- I want to show the calculated results in the textboxes in the form itself:

<td class="field"><input type="text" name="nbnm" id="nbnm" value="<?php echo $nbnm; ?>" /></td>
<td class="field"><input type="text" name="twkg" id="twkg" value="<?php echo $twkg; ?>" />

^This is throwing an error: Undefined variable nbnm and twkg

Where am I going wrong?

php

3个回答

There are several problems with your code.

First, the variables that are established in the Calc class are not going to be directly accessible by code outside of the class declaration. Your code <?php echo $twkg; ?> is not going to work because of scope - the variable twkg does not exist in the global scope where you are outputting the HTML.

You can access those variables in the Calc class, but you've made them private. You will either have to make a getter method for those variables if they remain private (thus <?php echo $calc->getTwkg(); ?>) OR, make them public and access them using the arrow operator (thus <?php echo $calc->twkg; ?>).

As for the error message, for one, as has been pointed out, the post handling code needs to go above the form rendering code, otherwise the form will be rendered before the lower code has a chance to decide if there's an error or not. Second, I am not sure what the use of $_REQUEST['error'] is all about: set $error to false, check for errors, if there is one, stick the error message in it. Then your if looks like this:

 if ($error !== false) 
     echo '<div id="er"><span class="er">&nbsp;'.$error.'</span></div>';

Here are some general edits... you've got a lot of confusing stuff in there and I don't know what you're doing, so I just put this together in the way of a collection of tips. I suggest you use more descriptive variable names: instead of $nob and $bdmn, use $bore_diameter_minimum - that way it is easy to see what a variable should contain.

// Defining the "calc" class 
class Calc { 
     private  $vs = 0; 
     public  $nob = 0;  // note that this is public   
     private  $tw = 0; 

    public function calculateMet($b,$s) {  
        // do your calculations here
        $this->vs = $b * $s;

        // use $this->vs, $this->nob to change the private variables declared above
        if ($this->vs < $v)
        return false;

        // return true if the calculation worked
        return true;
    }

    // use public getters to return variables that are private
    public function getVs() {
        return $this->vs;
    } 

} 
$calc = new Calc(); 
$error = false;

if (isset($_POST['submit'])) {
    $bdmm = isset($_POST['bdmm']) ? $_POST['bdmm'] : false; 
    $sdmm = isset($_POST['sdmm']) ? $_POST['sdmm'] : false; 


    if(
        $bdmm == false || 
        strlen($bdmm) < 1 || 
        preg_match("/^-?([0-9])+\.?([0-9])+$/", $bdmm) == false
    ){ 
        $error = "Invalid Bore Dia.";
    } 

    if(
        $sdmm == false || 
        strlen($sdmm) < 1 || 
        preg_match("/^-?([0-9])+\.?([0-9])+$/", $bdmm) == false
    ){ 
        $error = "Invalid Screen Dia.";
    }

    if ($error !== false) {
        $result = $calc->calculateMet($bdmm,$sdmm);
        if ($result === false)
            $error = 'Calculation failed';
    }
}

// output an error message
if ($error !== false)
    echo '<div class="error">'.$error.'</div>';

echo 'Private test: '.$calc->getVs();
echo 'Public test: '.$calc->nob;
dqyknf4423
dqyknf4423 哎呀,看看编辑。 移动行$ error = false; 在if语句之上。
接近 9 年之前 回复
duan5362
duan5362 谢谢你的解释。 我试图实现你的代码,但它抛出了这个错误:未定义的变量:错误。 我不知道为什么。 我创建了一个新的php页面,只是复制了html和错误部分,但它给了我未定义的错误。
接近 9 年之前 回复



您需要在页面顶部移动php代码,因为您甚至在创建变量之前就访问它们。</ p>

</ div>

展开原文

原文

You need to move the php code on top of the page, because you are accessing variables before even they are created.

doufei5315
doufei5315 好的,我做到了,但仍然没有输出和相同的问题。
接近 9 年之前 回复




  1. 你需要以某种方式将$ error放入$ _REQUEST(因为你试图从那里得到它) 并且它不会自动存在)。 您应该使用$ _SESSION ['error']而不是$ error =“Error!” if(isset($ _ SESSION ['error'])){而不是if(isset($ _ REQUEST ['error'])){。</ p> </ li>

  2. 全部移动 从底部到顶部的代码。 我没有仔细研究过代码,但似乎脚本在设置之前没有机会设置变量。</ p> </ li>
    </ ol>
    </ div>

展开原文

原文

  1. You need to put $error somehow into the $_REQUEST (because you try to get it from there and it is not there automatically). You should use $_SESSION['error'] instead of $error = "Error!" and if (isset($_SESSION['error'])){ instead of if (isset($_REQUEST['error'])){ .

  2. Move all the code from the bottom to the top. I haven't studied the code too closely, but it seems the script had no chance to set the variables before they were set.

dongxin5429
dongxin5429 我使用了SESSION但没有成功。 2.我将所有代码从下到上移动但仍然是相同的错误。
接近 9 年之前 回复
Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问