该例子演示了无限级分类的显示和添加.只用一个数据表实现记录无限级分类,关键是每条记录都记录了上一层类别的ID(parentid),然后通过一个递归函数来不断将类别显示出来.
*大类1
└二级小类1
└三级小类1
└四级小类1
└五级小类1
*大类2
└二级小类2
*大类3
数据库说明:数据库db.mdb,classTable表的结构:classid类别ID(自动增长) parentid 父级ID 默认为0 (0代表最高级) classname类别名,classdepth是为了记录类别的级数 ----------------------------------------------
| classid| classname| parentid | classdepth |
----------------------------------------------
主要代码:
//先取出最高级(parentid=0)的分类
程序代码
<%
set conn=server.createobject("adodb.connection")
conn.open "Provider=Microsoft.Jet.Oledb.4.0;data source="&server.MapPath("db.mdb")
set rs1=server.createobject("adodb.recordset")
sql1="select * from Classtable where parentid=0 order by classid"
rs1.open sql1,conn,1,1
if rs1.eof or rs1.bof then
response.write"还没分类!"
else
while not rs1.eof
id1=rs1("classid")
name1=rs1("classname")
response.write "*<a href='class.asp?id="&id1&"&name="&name1&"'>"&name1&"</a><br>"
parentid1=rs1("parentid")
call reclass(id1)
rs1.movenext
wend
end if
rs1.close
set rs1=nothing
sub reclass(id)
'递归调用函数,生成一个类别代码
set rs=server.createobject("adodb.recordset")
sql="select * from classtable where parentid="&id
rs.open sql,conn,1,1
i=1
while not rs.eof
id0=rs("classid")
classname0=rs("classname")
parentid0=rs("parentid")
classdepth0=rs("classdepth")
brstr=""
for j=1 to classdepth0
brstr=" "&brstr
next
response.write(brstr&"└<a href='class.asp?id="&id0&"&name="&classname0&"'>"&classname0&"</a><br>")
call reclass(id0)
rs.movenext
i=i+1
wend
rs.close
set rs=nothing
end sub
if request("a")="add" then
call add
end if
if request("name")<>"" then
%>
<table width="80%" align="center" cellpadding="0" cellspacing="0">
<form action="class.asp?a=add&id=<%=request("id")%>" method="post">
<tr>
<td> </td>
<td>在<font color="#FF0000"><%=request("name")%></font>添加小类</td>
</tr>
<tr>
<td>类别名:</td>
<td><input name="classname" type="text" id="classname"></td>
</tr>
<tr>
<td> </td>
<td><input type="submit" name="Submit" value="提交"></td>
</tr>
</form>
</table>
<%end if
sub add '添加类别
id=request("id")
classname=request("classname")
set rs=server.createobject("adodb.recordset")
rs.open "select parentid,classdepth from classtable where classid="&id,conn,1,1
parentid=rs(0)
classdepth=rs(1)+1
rs.close
set rs=nothing
sql="Insert INTO classtable (classname,parentid,classdepth) values ('"&classname&"',"&id&","&classdepth&")"
conn.execute sql
response.Write"<script>alert('添加成功!');location.href='class.asp';</script>"
end sub
%>