Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8029629
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 5, 20262026-06-05T00:29:34+00:00 2026-06-05T00:29:34+00:00

Problem: I am trying to delete all sublevels of a category by using a

  • 0

Problem:

I am trying to delete all sublevels of a category by using a class. Currently I can only make it delete two sublevels, not three.

The database table:

CREATE TABLE betyg_category (
  CID int(11) NOT NULL AUTO_INCREMENT,
  Item varchar(100) NOT NULL,
  Parent int(11) NOT NULL DEFAULT '0',
  PRIMARY KEY (CID)
) ENGINE=InnoDB  DEFAULT CHARSET=utf8;

The PHP class:

<?php
class ItemTree 
{ 
   var $itemlist = array();

   function ItemTree($query)
   {
      $result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());

      while ($row = mysql_fetch_assoc($result)) 
      {
         $this->itemlist[$row['CID']] = array(
           'name'   => $row['Name'],
           'parent' => $row['Parent']
         );
      }
   }

   function get_tree($parent, $with_parent=0)
   {
      $item_tree = array();

      if ($with_parent == 1 && $parent != 0) 
      {
         $item_tree[$parent]['name'] = $this->itemlist[$parent]['name'];
         $item_tree[$parent]['parent'] = $this->itemlist[$parent]['parent'];
         $item_tree[$parent]['child'] = $this->get_tree($parent);

         return $item_tree;
      }

      foreach ($this->itemlist as $key => $val) 
      {
         if ($val['parent'] == $parent) 
         {
               $item_tree[$key]['name'] = $val['name'];
               $item_tree[$key]['parent'] = $val['parent'];
               $item_tree[$key]['child'] = $this->get_tree($key);
         }
      }

      return $item_tree;
   }

   function make_optionlist ($id, $class='', $delimiter='/')
   {
      $option_list = '';

      $item_tree = $this->get_tree(0);

      $options = $this->make_options($item_tree, '', $delimiter);

      if (!is_array($id)) 
      {
         $id = array($id);
      }

      foreach($options as $row) 
      {
         list($index, $text) = $row;
         $selected = in_array($index, $id) ? ' selected="selected"' : '';
         $option_list .= "<option value=\"$index\" class=\"$class\"$selected>$text</option>\n";
      }

      return $option_list;
   }

   function make_options ($item_tree, $before, $delimiter='/')
   {
      $before .= empty($before) ? '' : $delimiter;

      $options = array();

      foreach ($item_tree as $key => $val) 
      {
         $options[] = array($key, '-&nbsp;'.$before.$val['name']);
         if (!empty($val['child'])) {
            $options = array_merge($options, $this->make_options($val['child'], $before.$val['name'], $delimiter));
         }
      }

      return $options;
   }

   function get_navlinks ($navid, $tpl, $startlink='', $delimiter=' &raquo; ')
   {
      // $tpl typ: <a href="index.php?id={id}" class="navlink">{name}</a>

      $search = array('{id}', '{name}');

      $navlink = array();

      while (isset($this->itemlist[$navid])) 
      {
         $replace = array($navid, $this->itemlist[$navid]['name']);
         $navlink[] = str_replace($search, $replace, $tpl);
         $navid = $this->itemlist[$navid]['parent'];
      }

      if (!empty($startlink)) 
      {
         $navlink[] = str_replace($search, array(0, $startlink), $tpl);
      }

      $navlink = array_reverse($navlink);

      return implode($delimiter, $navlink);
   }

   function show_tree ($parent=0, $tpl='%s', $ul_class='', $li_class='')
   {
      $item_tree = $this->get_tree($parent);

      return $this->get_node($item_tree, $parent, $tpl, $ul_class, $li_class);
   }

   function get_node ($item_tree, $parent, $tpl, $ul_class, $li_class)
   {
      // $tpl typ: <a href="item.php?id={id}" class="treelink" style="color:blue">{name}</a>

      $search = array('{id}', '{name}'); 

      $output = "\n<ul class=\"$ul_class\">\n";

      foreach ($item_tree as $id => $item) 
      {
         $replace = array($id, $item['name']);
         $output .= "<li class=\"$li_class\">".str_replace($search, $replace, $tpl);
         $output .= !empty($item['child']) ? "<br />".$this->get_node ($item['child'], $id, $tpl, $ul_class, $li_class) : '';
         $output .= "</li>\n";
      }

      return $output . "</ul>\n"; 
   }

   function get_id_in_node ($id)
   {
      $id_list = array($id);

      if (isset($this->itemlist[$id])) 
      {
         foreach ($this->itemlist as $key => $row) 
         {
            if ($row['parent'] == $id) 
            {
               if (!empty($row['child'])) 
               {
                 $id_list = array_merge($id_list, get_id_in_node($key));
               } else 
               {
                 $id_list[] = $key;
               }
            }
         }

      }
      return $id_list;
   }

   function get_parent ($id)
   {
      return isset($this->itemlist[$id]) ? $this->itemlist[$id]['parent'] : false;
   }

   function get_item_name ($id)
   {
      return isset($this->itemlist[$id]) ? $this->itemlist[$id]['name'] : false;
   }
}
?>

Scenario:

Say you have the following structure in a :

  • Literature
  • — Integration of sources
  • —- Test 1

It will result in the following in the database table:

Categories

When I try to delete this sublevel, it will leave the last sublevel in the database while it should delete it. The result will be:

Deleted categories

The PHP code:

//Check if delete button is set
if (isset($_POST['submit-deletecategory'])) 
{
    //Get $_POST variables for category id
    $CategoryParent = intval($_POST['CategoryList']);

    //Check if category is selected
    if ($CategoryParent != "#") 
    {
        //Get parent category and subsequent child categories
        $query = "SELECT CID, Item AS Name, Parent FROM " . TB_CATEGORY . " ORDER BY Name";
        $items = new ItemTree($query);

        if ($items->get_item_name($_POST['CategoryList']) !== false) 
        {
            //Build up erase list
            $CategoryErase = $items->get_id_in_node($CategoryParent);
            $CategoryEraseList = implode(", ", $CategoryErase);
        } 
        else 
        {
            $CategoryEraseList = 0;
        }

        //Remove categories from database
        $query = "DELETE FROM " . TB_CATEGORY . " WHERE CID IN ($CategoryEraseList)";
        $result = mysql_query($query) or die ('Database Error (' . mysql_errno() . ') ' . mysql_error());

       //Return a confirmation notice
       header("Location: settings.php");
       exit;
    }
}

Thank you in advance for any guidance I can get to solve the issue.

  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-05T00:29:35+00:00Added an answer on June 5, 2026 at 12:29 am

    Here is a way to do it : use a recursive function, which will first look for the leaf item (the deepest in your tree). You remove children first, then the parent. And for each child, you remove child’s children first, etc…

    deleteSub(1);
    
    function deleteSub($cat_id) {
        $request = "SELECT * FROM ". TB_CATEGORY ." WHERE Parent = ".$cat_id;
        $results = mysql_query($request);
        while($child = mysql_fetch_array($results)) 
        {
            deleteSub($child["CID"]);
        }
        $request = "DELETE FROM ". TB_CATEGORY ." WHERE CID = ".$cat_id;
        return mysql_query($request);
    }
    

    A better way could be use this kind of recursive function to store CIDs in an array, then make a single DELETE request, but I think you’ll be able to adapt this code.

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

Trying to add the ability to delete a Folder using FTP and all subfolders
I am trying to write a shell script to delete all the sub directories
im trying to delete this origin thing so i can actually run the tutorial
I am not sure how to approach this problem: 'Player' class maintains a list
I'm trying to delete all the cookies that my site uses but from reading
i am having a problem with the way that i am trying to delete
My problem is I want to delete records from two tables, deleting the records
I'm trying to create a script to delete all files in a folder and
I have a problem when I'm trying to delete an image file. I always
hi all i am getting a problem while i attenpting to delete a row

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.