dtmtu02882 2019-01-31 02:39
浏览 24
已采纳

在PHP中填充类别匹配表中的复选框

I have a list of categories associated with a post in a database. Here is an example of what the categories look like in the database (PID = PostID and CATID = Category ID).

PID   CATID
 1      34
 1      12
 1      15

I have a php form that displays a list of all categories next to an array of checkboxes using name = "catid[]". I need to know the best practice to query the database and and write PHP code so that it pre-check the boxes for categories 12, 15, and 34 using the CHECKED attribute in each appropriate form checkbox for the POST with an PID of 1.

Here is the function that produces the list of categories.

function categoryTree($pid, $cat_type, $parentid = 0, $sub_mark = ''){
global $db;

$query = $db->query("SELECT * FROM categories WHERE parentid = $parentid and cat_type = '$cat_type' ORDER BY parentid, category ASC");

if($query->num_rows > 0){
    while($row = $query->fetch_assoc()){
        if ($row['parentid'] == 0) {
            echo '<div><label><span class="font-md">'.$sub_mark.$row['category']."</span></label></div>";
        } else {
            echo '<div class="checkbox" style="padding-left:15px;padding-top:5px;padding-bottom:5px;"><label><input name="catid[]" type="checkbox" value="'.$row['catid'].'" class="checkbox style-0"><span>'.$sub_mark.$row['category']."</span></label></div>";
        }
        categoryTree($cat_type, $row['catid'], $sub_mark.' ');
    }
    }
}

Thanks in advance.

  • 写回答

1条回答 默认 最新

  • duannian4784 2019-01-31 03:11
    关注

    Assuming you have the array of checked categories ids as $checkedCategories you could do something like this.

    <?php foreach ($categories as $category) : ?>
       <input name="catid[]" 
           value="<?php echo $category['id']; ?>" 
           <?php echo in_array($category['id'], $checkedCategories)? 'checked':'' ?>>
       <?php echo $category['name']; ?>
       <br>
    <?php endforeach; ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效