2015-06-21 53 views
0

好吧,我會告訴你的代碼,你應該從中明白我想要什麼,問題是它沒有從它接觸同一頁面上的其他PHP標籤內的一個PHP標籤識別變量。 PHP ...如何「看」 PHP變量在多個<?php ?>

<form action="contact.php" method="POST"> 
     <p>Name: <input type="text" name="name"><?php $nameErr=' '; echo $nameErr; ?></p> 
     <p>Email: <input type="email" name="email"><?php $emailErr=' '; echo $emailErr; ?></p> 
     <p>Message:</p> <textarea name="message" rows="10" cols="50"></textarea><br /> 
     <p><?php $messageErr= ' '; echo $messageErr; ?></p> 
     <button type="submit" value="Submit" name="Submit1">Submit</button> 
</form> 
<?php 
    if (isset($_POST['Submit1'])) { 

     $name = $_POST['name']; 
     $email= $_POST['email']; 
     $message= $_POST['message']; 
     $formcontent= "From: $name \n Message: $message"; 
     $recipient= "[email protected]"; 
     $subject= "Contact Form"; 
     $mailheader= "From: $email \r\n"; 
     if(strlen($name)==0) { 
      $nameErr = "Name is required <br>"; 
      die(); 
     } 
     elseif(strlen($email)==0) { 
      $emailErr = "Email is required"; 
      die(); 
     } 
     elseif(strlen($message)==0) { 
      $messageErr "Message is required <br>"; 
      die(); 
     } 
     else { 

      echo "$name, thank you for submiting message"; 
     } 
    } 
?> 

我所做的所有$ varErr變量空字符串時默認contact.php你什麼也看不到,當你第一次進入,但是當你提交表單IF檢查,如果字段爲空,如果是空的我要以表單字段行內回聲$ varErr該字段($ nameErr或$ emailErr,$ messageErr將在textarea的事業領域去我喜歡這樣吃)

希望你能理解我想要什麼,我已經完成一切只是形式,我做.. Ofcourse我可以通過在形狀誤差呼應空表單字段避免這一切的,但是這不是我想要的東西......

+0

PSS:你缺少'='靠近你'$ messageErr 「消息需要
」;' –

回答

0

在您的原始代碼$nameErr,$emailErr$messageErr顯示之後被更改。

如果您是這樣的:

<?php $something = "value1"; 
echo $something; 
$something = "value2"; 
?> 

它會顯示在屏幕上value1

應該是這樣的:

<?php 
     $nameErr=''; 
     $emailErr=''; 
     $messageErr= ''; 
     if ($_POST) { 

      $name = $_POST['name']; 
      $email= $_POST['email']; 
      $message= $_POST['message']; 
      $formcontent= "From: $name \n Message: $message"; 
      $recipient= "[email protected]"; 
      $subject= "Contact Form"; 
      $mailheader= "From: $email \r\n"; 
      if(strlen($name)==0) { 
       $nameErr = "Name is required <br>"; 
      } 
      elseif(strlen($email)==0) { 
       $emailErr = "Email is required"; 
      } 
      elseif(strlen($message)==0) { 
       $messageErr = "Message is required <br>"; 
      } 
      else { 

       echo "$name, thank you for submiting message"; 
      } 
     } 
    ?> 
    <form action="" method="POST"> 
      <p>Name: <input type="text" name="name"><?php echo $nameErr; ?></p> 
      <p>Email: <input type="email" name="email"><?php echo $emailErr; ?></p> 
      <p>Message:</p> <textarea name="message" rows="10" cols="50"></textarea><br /> 
      <p><?php echo $messageErr; ?></p> 
      <button type="submit" value="Submit" name="Submit1">Submit</button> 
    </form> 

此外,我除去die(),因爲否則它使出口before showing the error. However you don't need模具()here because it sends the form only if server runs the last else`聲明,只有在所有領域都完成。