请您指导我如何使用php和mysql在下拉列表中创建无限的类别和子类别?
我是他们面前的子类别。例如,第一个子类别---和第二个级别-----等等: 我想实现这样的事情: -
<select name="category">
<option value="1">Root</option>
<option value="3">- Sub </option>
<option value="4">- - Sub</option>
<option value="5">Root</option>
<option value="6">- Sub </option>
<option value="7">- - Sub</option>
</select>
这是我到目前为止的代码
function get_category($parentID = 0){
global $mysqli;
$html = '';
// Prepare the query
$stmt = $mysqli->prepare("SELECT CategoryID, Title
FROM category
WHERE ParentID =?");
// Bind param
$stmt->bind_param('i', $parentID);
// Execute the query
$stmt->execute();
// Store the result
$stmt->store_result();
// Bind the result
$stmt->bind_result($categoryID, $title);
while($stmt->fetch()){
$html .= "<option value=\"$categoryID\">$title</option>";
$child = $mysqli->prepare("SELECT CategoryID
FROM category
WHERE ParentID =?");
// Execute the query
$child->bind_param('i', $categoryID);
$child->execute();
// Store the result
$child->store_result();
// Bind the result
$has_child = NULL;
$has_child = $child->num_rows;
if($has_child){
$html .= get_category($categoryID);
}
}
return $html;
}
echo '<select name="category">';
print(get_category());
echo '</select>';
感谢任何帮助
答案 0 :(得分:0)
请参阅此link。它的格式为mysql格式
同时检查
<?php
// Get listing of base categories
$sql="SELECT cat_id, cat_name FROM cat_table where cat_parent='0' ORDER BY cat_name asc";
$basecat = mysql_query($sql) or die($sql);
print"<select name=\"category\">";
while($cat_list=mysql_fetch_array($basecat)){
if ($cat_list[0]==$cur_cat){$test= ' selected';}else{$test='';}
print '<option value="'.$cat_list[0].'"'.$test.'>'.$cat_list[1].'</option>';
sub_cat($cat_list[0]);// this calls the function for sub cats
}
print'</select>';
// ***********************************************************************
// Sub-Category Function
function sub_cat($cat_num){
$subcat = mysql_query("SELECT cat_id, cat_name FROM cat_table where cat_parent='$cat_num' ORDER BY cat_name asc");
while($sub_cat_list = mysql_fetch_array($subcat)){
if ($sub_cat_list[0]==$cur_cat){$test=' selected';}else{$test='';}
print '<option value="'.$sub_cat_list[0].'"'.$test.'> '.$sub_cat_list[1].'</option>';
}
}
// ***********
像这种格式的结果
<select name="category">
<option value="4">Advertising</option>
<option value="8"> Newspaper</option>
<option value="10"> Radio</option>
<option value="9"> Television</option>
<option value="2">Autos</option>
<option value="5"> Chevy</option>
<option value="7"> Dodge</option>
<option value="6"> Ford</option>
<option value="3">Marketing</option>
</select>
更新了Link