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; ?>
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 matlab(相关搜索:紧聚焦)
  • ¥15 基于51单片机的厨房煤气泄露检测报警系统设计
  • ¥15 路易威登官网 里边的参数逆向
  • ¥15 Arduino无法同时连接多个hx711模块,如何解决?
  • ¥50 需求一个up主付费课程
  • ¥20 模型在y分布之外的数据上预测能力不好如何解决
  • ¥15 processing提取音乐节奏
  • ¥15 gg加速器加速游戏时,提示不是x86架构
  • ¥15 python按要求编写程序
  • ¥15 Python输入字符串转化为列表排序具体见图,严格按照输入