2016-08-11 37 views
1

我正在爲我的項目使用PHP和MYSQLI。我有一個表單,其中包含一個文本輸入字段和三個複選框。當用戶選中三個框中的兩個並提交表單而不填充文本輸入字段時,我顯示錯誤。表單在PHP中提交錯誤時丟失了複選框值

現在我想實現的是當顯示錯誤時,用戶檢查的特定複選框不應該被取消選中。請理解,表單中的所有複選框的類別字段都是相同的。

我的表單例子如下:

<?php if(isset($_POST['submit'])) {  
    $full_name=$db->real_escape_string($_POST["full_name"]); 
    $checkbox = implode(',', $_POST["fruits"]); 

    if(empty($checkbox)) { 
     $errors = 'Please choose at least one fruit.'; 
    } 

    if(!isset($errors)) { 
     // I am inserting the data 
    } else { 
     $errors; 
    } 
} 
?> 

<form method="post" action="add.php"> 
<input type="text" name="full_name"> 
<input type="checkbox" name="fruits[]" value="Apple"> 
<input type="checkbox" name="fruits[]" value="Banana"> 
<input type="checkbox" name="fruits[]" value="Carrot"> 
<input type="submit" name="submit" value="Submit"> 
</form> 
+0

你能發表PHP代碼嗎? – pmahomme

+0

我已更新我的代碼以匹配您的PHP代碼。 – FrankerZ

回答

0

做一個in_array()檢查,看看水果是數組中,然後回聲出checked="checked"把它選中該複選框(再次)。

<?php 
if(isset($_POST['submit'])) { 
    $errors = array(); 

    $full_name = $db->real_escape_string($_POST["full_name"]); 
    //Initialize empty array (In case fruits isn't sent, if they didn't check any boxes) 
    $fruits = array(); 

    //We get an array? Cool, set it to $fruits 
    if (isset($_POST['fruits']) && is_array($_POST['fruits'])) { 
     $fruits = $_POST['fruits']; 
    } 

    if (empty($full_name)) { 
     $errors[] = 'Please enter your name.'; 
    } 

    if(empty($fruits)) { 
     $errors[] = 'Please choose at least one fruit.'; 
    } 

    if(empty($errors)) 
    { 
     //Change $fruits into a string 
     $fruits = implode(', ', $fruits); 
     // I am inserting the data 
    } else { 
     foreach ($errors as $error) 
     { 
      echo '<p class="error">', $error, '</p>'; 
     } 
    } 
} 

?> 

<form method="post" action="add.php"> 
    <input type="text" name="full_name" value="<?=htmlspecialchars($_POST['full_name'])?>" /> 
    <input type="checkbox" name="fruits[]" value="Apple"<?=(in_array('Apple', $fruits) ? ' checked="checked"' : '') ?> /> 
    <input type="checkbox" name="fruits[]" value="Banana"<?=(in_array('Banana', $fruits) ? ' checked="checked"' : '') ?> /> 
    <input type="checkbox" name="fruits[]" value="Carrot"<?=(in_array('Carrot', $fruits) ? ' checked="checked"' : '') ?> /> 
    <input type="submit" name="submit" value="Submit" /> 
</form> 
+1

感謝FrankerZ的快速回復,這解決了我的問題,並按預期工作。再次感謝,祝你有美好的一天。 – user2945468

相關問題