2012-08-31 137 views
0

海兰那里,删除树结构数据递归

我有一些树结构数据在我的sqlite的表,并希望与PHP递归删除。数据是这样的:

 
Id ParentId 
0  -1 
1  0 

功能:

/** 
* Delete a category with all it's subcategories 
* 
* @param {number} id The id of the category which should be deleted 
* @return {number} The number of categories deleted 
* @throws {Exception} Throws an exception with some description text if anything goes wrong 
*/ 
public function deleteCategory($id) { 
    static $catCnt = 0; 

    Helper::log("deleteCategory: id = $id"); 

    try { 
     // Open database-connection 
     $this->openDatabase(); 

     // Remove all subcategories recursively 
     $stmtSubs = $this->_db->prepare("SELECT Id FROM categories WHERE ParentId = :id"); 
     $stmtSubs->bindParam(":id", $id, PDO::PARAM_INT); 
     $stmtSubs->execute(); 
     while ($row = $stmtSubs->fetch(PDO::FETCH_ASSOC)) { 
      Helper::log("deleteCategory: call recursively to delete subcategory with id = " . $row["Id"]); 
      $this->deleteCategory($row["Id"]); 
     } 

     // All subcategories have been removed -> Now it's time to remove the category itself 
     $stmt = $this->_db->prepare("DELETE FROM Categories WHERE Id = :id"); 
     $stmt->bindParam(":id", $id, PDO::PARAM_INT); 

     Helper::log("deleteCategory: before execution, id = $id"); 
     $stmt->execute(); 

     // The code from here on never gets executed... 
     Helper::log("deleteCategory: after execution, id = $id"); 

     $catCnt += $stmt->rowCount(); 

     return $catCnt; 
    } catch (Exception $ex) { 
     throw new Exception("Deletion of category failed:<br>" . $ex->getMessage()); 
    } 
} 

如果我叫带参数0这个功能,我得到这样的输出:

31.08.2012 09:39:58: deleteCategory: id = 0 
31.08.2012 09:39:58: deleteCategory: call recursively to delete subcategory with id = 1 
31.08.2012 09:39:58: deleteCategory: id = 1 
31.08.2012 09:39:58: deleteCategory: before execution, id = 1 
// Here should be the "after execution"-entry, but instead it "waits" half a minute and starts the whole execution from the beginning... 
31.08.2012 09:40:28: deleteCategory: id = 0 
31.08.2012 09:40:44: deleteCategory: call recursively to delete subcategory with id = 1 
31.08.2012 09:40:44: deleteCategory: id = 1 
31.08.2012 09:40:44: deleteCategory: before execution, id = 1 

正如你所看到的它执行得很好,直到它实际上应该删除ID为1的子类。execute-command从来没有完成,相反,它似乎没有做任何事半分钟,然后它开始从beginnin的整个递归摹ID为0

后的第二个“尝试”,它只是一个内部服务器错误返回(“服务器遇到一个内部错误或配置错误,无法完成您的请求......”)

如果我用参数1调用这个函数,一切正常,因为递归永远不会被调用。

这里发生了什么事?

感谢,

Mik的

回答

0

与此周围挣扎像半天,决定将它张贴在这里,贴在这里,发帖之后不得不重新审视它,看到了问题:

递归调用“$ this-> openDatabase();”是所有邪恶的来源...

谢谢;)