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.