使用PHP删除所有类别的n-lavel

时间:2019-04-22 10:32:19

标签: php

function delete_subcats($id) {
    global $con;
    $sql = "select * from `add_category` where `id` = ".$id;
    $res = mysqli_query($con,$sql);
    if(mysqli_num_row($res)>0){
        while($row = mysqli_fetch_assoc($res)){
            delete_subcats($row['id']);
        }
    }

    mysqli_query($con,"delete from `add_category` where `id` = ".$id);
}

1 个答案:

答案 0 :(得分:0)

您可以提供父ID的外键,而不是执行简单删除查询后。

OR

您可以使用递归函数。

function delete_category($cat_id, $table = "nested_category") {
        $query = $this->db->select('id,pid')
                        ->from($table)
                        ->where('pid', $cat_id)
                        ->get()->result();
        foreach ($query as $row)
            $this->delete_category($row->id);
        $this->db->delete($table, array("id" => $cat_id));
    }

OR

function delete_subcats($id) {
    global $con;
    $sql = "select * from `add_category` where `pid` = ".$id;
    $res = mysqli_query($con,$sql);
    if(!empty($res)){
        while($row = mysqli_fetch_assoc($res)){
            delete_subcats($row['id']);
        }
    }

    mysqli_query($con,"delete from `add_category` where `id` = ".$id);
}