2012-08-31 134 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();」是所有邪惡的來源...

謝謝;)