2011-11-01 2 views
-1

calculate 함수를 호출하여 같은 페이지에 표시하려는 양식이 있습니다. 오류가 있으면 동일한 페이지의 span 태그에 표시되어야합니다. 여기 동일한 페이지의 양식에 결과 제출 및 표시

내가 지금 무엇을, 난 문제로 실행 해요 :

index.php를 [업데이트]] :

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

주로 나는에 표시 할 두 가지가 있습니다 형태 : 에러가있는 경우는 스팬 태그에 에러를 표시한다

1- -

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

이 작업을 수행했지만 텍스트 상자가 비어 있어도 오류가 발생하지 않습니다.

2 I 양식 자체에 텍스트 상자에서 계산 된 결과를 보여주고 싶은 :

<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; ?>" /> 

^이 오류를 던지고을 : Undefined variable nbnm and twkg

어디서 잘못된 것입니까?

답변

1

코드에 몇 가지 문제가 있습니다.

먼저 Calc 클래스에 설정된 변수는 클래스 선언 외부의 코드에서 직접 액세스 할 수 없습니다. 코드 <?php echo $twkg; ?>은 범위 때문에 작동하지 않습니다. twkg 변수는 HTML을 출력하는 전역 범위에 존재하지 않습니다.

Calc 클래스에서 변수에 액세스 할 수 있지만 비공개로 설정했습니다. 개인 변수 (즉, <?php echo $calc->getTwkg(); ?>)이거나 변수를 공개하고 화살표 연산자 (따라서 <?php echo $calc->twkg; ?>)를 사용하여 액세스하는 경우 해당 변수에 대한 getter 메서드를 만들어야합니다.

오류 메시지에 관해서는 지적했듯이 사후 처리 코드는 양식 렌더링 코드 위로 올라와야합니다. 그렇지 않으면 양식이 렌더링되어 하위 코드에 오류가 있는지 결정할 수 있습니다. 오류 여부. 둘째로, 나는 $_REQUEST['error']의 용도가 무엇인지 모르겠습니다. $error을 false로 설정하고, 오류가 있는지 확인하고, 오류 메시지가 있으면 거기에 붙여 넣으십시오.그렇다면이 같은 외모 경우 : 여기

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

은 몇 가지 일반적인 편집입니다 ... 당신은 거기에 혼란 물건을 많이 가지고 그리고 난 당신이 무슨 일을하는지 모르는, 그래서 난 그냥이를 넣어 함께 팁 모음으로 보다 구체적인 변수 이름을 사용하는 것이 좋습니다 : $nob$bdmn 대신 $bore_diameter_minimum을 사용하십시오. 그러면 변수에 무엇이 들어 있어야하는지 쉽게 알 수 있습니다.

// 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; 
+0

설명해 주셔서 감사합니다. 귀하의 코드를 구현하려하지만이 오류가 발생합니다 : '정의되지 않은 변수 : 오류'. 이유가 확실하지 않습니다. 나는 새로운 PHP 페이지를 만들었고 html과 오류 부분을 복사했다. 그러나 그것은 나에게'undefined' 오류를주고있다. – input

+0

와우, 편집을 참조하십시오. if 문 바로 위의'$ error = false; '행을 이동하십시오. –

0

변수가 생성되기 전에 변수에 액세스하기 때문에 PHP 코드를 페이지 상단으로 이동해야합니다.

+0

그래, 나도 그래도 출력물과 같은 문제가 발생했습니다. – input

0
  1. $ _REQUEST에 $ error를 넣어야합니다 (자동으로 거기에서 가져 오기 때문에 자동으로 생성되지 않으므로). $ error = "Error!"대신 $ _SESSION [ 'error']을 사용해야합니다. if (isset ($ _REQUEST [ 'error']))) {} 대신에 if (isset ($ _ SESSION [ 'error'])) {

  2. 아래에서 위로 모든 코드를 이동하십시오. 나는 코드를 너무 가깝게 연구하지는 못했지만 스크립트가 설정되기 전에 변수를 설정할 기회가 없었던 것으로 보인다.

+0

1. 나는 SESSION을 사용했으나 성공하지는 못했다. 2. 모든 코드를 아래에서 위로 이동했지만 여전히 동일한 오류가 발생했습니다. – input

관련 문제