dqqfuth6736 2011-11-01 18:29
浏览 405
已采纳

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

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?

  • 写回答

3条回答 默认 最新

  • duanjing1023 2011-11-01 18:44
    关注

    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;
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(2条)

报告相同问题?

悬赏问题

  • ¥15 高德地图点聚合中Marker的位置无法实时更新
  • ¥15 DIFY API Endpoint 问题。
  • ¥20 sub地址DHCP问题
  • ¥15 delta降尺度计算的一些细节,有偿
  • ¥15 Arduino红外遥控代码有问题
  • ¥15 数值计算离散正交多项式
  • ¥30 数值计算均差系数编程
  • ¥15 redis-full-check比较 两个集群的数据出错
  • ¥15 Matlab编程问题
  • ¥15 训练的多模态特征融合模型准确度很低怎么办