du16178 2012-08-17 15:50
浏览 815
已采纳

多级菜单项删除递归功能

I want to delete category from multilevel menu with recursion function. To understand situation more carefully , lets take a look first at mysql table structure

CREATE TABLE IF NOT EXISTS menu(
id INT(5) NOT NULL AUTO_INCREMENT PRIMARY KEY,
p_id INT(5),
sort_id INT(5) NOT NULL,
title VARCHAR(50) CHARSET utf8 COLLATE 'utf8_unicode_ci' NOT NULL,
);

it looks like this when it is retrieved

  id  |  p_id  |  sort_id  | title  |

   1  |    0   |     1     | root1  |
   2  |    1   |     1     |  sub of root1
   3  |    0   |     2     | root2  |
   4  |    2   |     1     |  sub of "sub of root1"
  ... |  ...   |    ...    |   ....
etc ...

I've written php script for delete category, here it is =>

function del_cat($connection,$id){
        if (!$connection->connect_errno){
        if ($connection->set_charset("utf8")){
            if ($r = $connection->query("SELECT id FROM menu WHERE p_id=" . $id . "")){
            if ($r->num_rows>0){
                while ($row = $r->fetch_assoc()){
                del_cat($connection,$row['id']);
                }
            } else {
                $connection->query("DELETE FROM menu WHERE id=" . $id . "");
            }
            $r->free();
            }
        }
        }
    }

$connection variable is a just mysql connection object, and $id is id in table.

It works just fine when I'm deleting one row ( I mean when category doesn't have a child , sub categories), for example 1 | 0 | 1 | root1 |, but when I want to delete for example 4 | 2 | 1 | sub of "sub of root1" it doesn't delete category with sub categories . Any idea how to solve this problem ? thanks

  • 写回答

1条回答 默认 最新

  • douxianglu4370 2012-08-17 16:03
    关注

    The delete is only in else so you never actually delete the parent category. I think you need something like:

       del_cat($connection, $row['id']);
       $connection->query("DELETE ...");
    } else {
       $connection->query("DELETE ...");
    

    By the way you should escape the ID input.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 高价求中通快递查询接口
  • ¥15 解决一个加好友限制问题 或者有好的方案
  • ¥15 关于#java#的问题,请各位专家解答!
  • ¥15 急matlab编程仿真二阶震荡系统
  • ¥20 TEC-9的数据通路实验
  • ¥15 ue5 .3之前好好的现在只要是激活关卡就会崩溃
  • ¥50 MATLAB实现圆柱体容器内球形颗粒堆积
  • ¥15 python如何将动态的多个子列表,拼接后进行集合的交集
  • ¥20 vitis-ai量化基于pytorch框架下的yolov5模型
  • ¥15 如何实现H5在QQ平台上的二次分享卡片效果?