2017-01-22 54 views
3

我試圖在複選框未被選中時顯示錯誤消息。我已經設法完成輸入字段,但不確定如何使用複選框完成它。這是我到目前爲止:驗證複選框是否已被選中

<?php 
    # check if data has been posted 
    if (!empty($_POST)) { 
     # keep track validation errors 
     $author_error = null; 
     $categories_error = null; 

     # keep track of post values 
     $author = $_POST['author']; 
     $categories = $_POST['categories']; 

     # validate input 
     if (empty($author)) { 
      $author_error = 'Please select author'; 
      $valid = false; 
     } 

     if (empty($categories)) { 
      $categories = 'Please select categories'; 
      $valid = false; 
     } 

     # if data is valid, insert into the database 
     if ($valid) { 

     } 
    } 
    ?> 

     <div class="control-group <?php if (!empty($author_error)){ echo 'error'; } ?>"> 
      <label class="control-label">Author</label> 
      <div class="controls"> 
       <select name="author" id="author"> 
        <option value="">Select one</option> 
        <?php $sql2 = 'SELECT id, name FROM author'; 
        foreach ($dbConnection->query($sql2) as $data2) { ?> 
        <option value="<?php echo $data2['id']; ?>" 
         <?php if(isset($author) && $author == $data2['id']) { echo 'selected'; } ?>> 
         <?php echo $data2['name']; ?> 
        </option> 
        <?php } ?> 
       </select> 
       <?php if (!empty($author_error)) { echo '<span class="help-inline">' . $author_error . '</span>'; } ?> 
      </div> 
     </div> 

     <div class="control-group <?php if (!empty($categories_error)){ echo 'error'; } ?>"> 
      <fieldset> 
      <legend class="control-label">Categories:</legend> 
      <?php $sql3 = 'SELECT id, name FROM category'; 
      foreach ($dbConnection->query($sql3) as $data3) { ?> 
      <div class="controls">  
       <label for="category<?php echo($data3['id']);?>"> 
        <input type="checkbox" name="categories" id="categories" value="<?php echo($data3['id']); ?>" 
        <?php if(isset($_POST['categories']) && in_array($data3['id'], $_POST['categories'])) { echo 'checked'; } ?>> 
        <?php echo($data3['name']); ?> 
       </label> 
      </div> 
      <?php } ?> 
      </fieldset> 
      <?php if (!empty($categories_error)) { echo '<span class="help-inline controls">' . $categories_error . '</span>'; } ?> 
     </div> 

我在哪裏出錯類別字段?

回答

3

檢查,如:

isset($_POST['categories']) 
+0

是啊,這是它存儲的錯誤消息。我是否應該使用相同的作者字段? –

+0

不,對於

1

線#62,但你檢查,如果$categories_error是空的您在使用可變$categories上線#19

+0

好點,didn'不要看那一個。 –