0

请您指导我如何使用 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>';

任何帮助表示赞赏

4

1 回答 1

0

请参阅此链接。它是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.'>&nbsp;&nbsp;&nbsp;'.$sub_cat_list[1].'</option>';
}
}
// ***********

结果像这种格式

<select name="category">
<option value="4">Advertising</option>
<option value="8">&nbsp;&nbsp;&nbsp;Newspaper</option>
<option value="10">&nbsp;&nbsp;&nbsp;Radio</option>
<option value="9">&nbsp;&nbsp;&nbsp;Television</option>
<option value="2">Autos</option>
<option value="5">&nbsp;&nbsp;&nbsp;Chevy</option>
<option value="7">&nbsp;&nbsp;&nbsp;Dodge</option>
<option value="6">&nbsp;&nbsp;&nbsp;Ford</option>
<option value="3">Marketing</option>
</select>

更新链接

于 2013-09-19T05:04:06.800 回答