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 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看