Php mysql recursive function to delete all child nodes in one table

// first action:

// find the deepest nodes if have any

   $child_kit = [ ];
   get_child_dir_ids( $fd_id, $child_kit );

   $wpdb->delete(
       $wpdb->prefix . 'table_A',
           array( 'dir_id' => $fd_id, 'eid' => $eid ),
           array( '%d', '%d' )
   );
   $wpdb->delete(
       $wpdb->prefix . 'table_A',
           array( 'parent_id' => $fd_id, 'eid' => $eid ),
           array( '%d', '%d' )
   );

   //delete all child nodes now

   if ( count($child_kit) > 0 ) {
       $dir_id_to_be_deleted = implode( ",", $child_kit );
       $query = "DELETE FROM {$wpdb->prefix}table_A WHERE eid={$eid} AND parent_id IN($dir_id_to_be_deleted)";
       $wpdb->query($query);
   }

// second action:

function get_child_dir_ids( $parent_id, &$child_kit ) {
    global $wpdb;

    $query  = "SELECT dir_id FROM {$wpdb->prefix}table_A WHERE parent_id=" . $parent_id;
    $dir_id = $wpdb->get_var( $query );
    if ( is_null( $dir_id ) ) {
        return $child_kit;
    } else {
        $child_kit[] = $dir_id;
        get_child_dir_ids( $dir_id, $child_kit );
    }

}

*** i have shown it in wordpress way but you can manage it in any programming language or platform you like********************************************************

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>