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 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 java 的protected权限 ,问题在注释里
  • ¥15 这个是哪里有问题啊?