PHP递归函数删除所有子节点导致stackoverflow
我的MySQL看起来像这样:(表的名称是类别)
'id', 'content', 'parent'
其中:
- id =类别的id
- 内容= some-text-we-dont-care-about
- Parent = 父级的 id 类别
这就是我现在正在尝试的:
function remrecurs($id) {
$qlist=mysql_query("SELECT * FROM category WHERE parent='$id'");
if (mysql_num_rows($qlist)>0) {
while($curitem=mysql_fetch_array($qlist)) {
remrecurs($curitem['parent']);
}
}
mysql_query("DELETE FROM category WHERE id='$id'");
}
由于某种原因,它不起作用并且崩溃.. 知道我做错了什么吗?
My MySQL looks like this: (the name of the table is category)
'id', 'content', 'parent'
where:
- id = the id of the category
- content =
some-text-we-dont-care-about - parent = the id of the parent
category
this is what I'm trying right now:
function remrecurs($id) {
$qlist=mysql_query("SELECT * FROM category WHERE parent='$id'");
if (mysql_num_rows($qlist)>0) {
while($curitem=mysql_fetch_array($qlist)) {
remrecurs($curitem['parent']);
}
}
mysql_query("DELETE FROM category WHERE id='$id'");
}
Which for some reason doesnt work and crashes ..
Any idea what I'm doing wrong ?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
问题出在递归调用中:
它应该是:
为什么?
你的目标是删除具有给定 id 的行。首先,您检查它是否有任何孩子。如果是,您需要在每个子级上调用递归删除,而不是再次在父级上调用。您再次在父级上递归调用该函数。这会导致无限递归调用,您会破坏堆栈并崩溃。
The problem is in the recursive call:
it should be:
Why?
Your objective is to delete the row with given id. First you check to see if it has any children. If yes you need to call the recursive delete on each of the children not on the parent again. You are calling the function recursively on the parent again..this leads to infinite recursive calls, you thrash the stack and crash.
或者,您可以让数据库处理这个问题。在 MySQL 中, InnoDB
ON DELETE CASCADE
将自动执行此操作。根节点应该以
NULL
作为父节点(而不是像有些人在邻接列表表上使用的那样0
)。Alternatively, you could let the database handle this. In MySQL, an InnoDB
ON DELETE CASCADE
will do this automatically.Root nodes should have
NULL
as parent (not0
as some people seem to employ on Adjancency List tables).