2012-03-18 39 views
4

我有一個表單,其操作設置爲自己。我想這樣做,以便返回先​​前輸入的值,如果您已經提交了一次表單(帶有錯誤),以便您不必完全重做表單。我有:與PHP的粘性窗體

<?php 

if (isset($_POST['submit'])) { 
$firstname= $_POST['firstname']; 
$lastname= $_POST['lastname']; 
$output_form= false; 

if ($firstname== "empty($firstname) && empty($lastname)) { 
echo "you forgot you first and last names!!"; 
$output_form= true; 
} 

if (!empty($firstname) && empty($lastname)) { 
echo "you forgot your last name."; 
$output_form= true; 
} 

if (empty($firstname) && !empty($lastname)) { 
echo "you forgot your firstname."; 
$output_form= true; 
} 

if (!empty($firstname) && !empty($lastname)) { 
echo "good job!!"; 
} 

} 

else 
{ 
$output_form= true; 
} 

if ($output_form) { 
?> 

<form method="post" action=" <?php echo $_SERVER['PHP_SELF']; ?>"> 
First Name: <input type="text" name="firstname" value="<?php echo $firstname ?>"/> 
Last Name: <input type="text" name="lastname" value="<?php echo $lastname ?>"/> 
<input type="submit" name="submit" value="submit"/> 
</form> 

<?php 
} 
?> 

如果表單尚未提交$output_form變量將在我的if語句返回true。但我得到一個錯誤,因爲變量$firstname$lastname尚未定義(因爲isset($_POST['submit']返回false值;該表單尚未提交)我可以做些什麼來保持我的表單「粘」?

+0

你可以寫一個錯誤發生? – safarov 2012-03-18 17:04:51

回答

3

設定的默認值來檢查你的變量

$firstname = ''; 
$lastname = ''; 

if(isset($_POST['submit'])) { 
    $firstname = $_POST['firstname']; 
    // ... 
} 
1

您在代碼的第8行有一個不需要的報價"。這是一個修復。

<?php 

if (isset($_POST['submit'])) { 
    $firstname = $_POST['firstname']; 
    $lastname = $_POST['lastname']; 
    $output_form = false; 

    if ($firstname == empty($firstname) && empty($lastname)) { 
     echo "{you 
} forgot you first and last names!!"; 
     $output_form = true; 
    } 

    if (!empty($firstname) && empty($lastname)) { 
     echo "you forgot your last name . "; 
     $output_form = true; 
    } 

    if (empty($firstname) && !empty($lastname)) { 
     echo "you forgot your firstname . "; 
     $output_form = true; 
    } 

    if (!empty($firstname) && !empty($lastname)) { 
     echo "good job!!"; 
    } 

} 

else 
{ 
    $output_form = true; 
} 

if ($output_form) { 
    ?> 

<form method="post" action=" <?php echo $_SERVER['PHP_SELF']; ?>"> 
    First Name: <input type="text" name="firstname" value="<?php echo $firstname ?>"/> 
    Last Name: <input type="text" name="lastname" value="<?php echo $lastname ?>"/> 
    <input type="submit" name="submit" value="submit"/> 
</form> 

<?php 
} 
?> 
0

$output_form = false;以上的if (isset($_POST['submit'])) {