delete.php 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. include '../connection.php';
  3. try {
  4. $params = json_decode(file_get_contents('php://input'));
  5. $db->beginTransaction();
  6. // get the left and right bounds of the node so we can delete it and all its descendants
  7. $statement = $db->prepare("select lft, rgt from list where id = $params->id");
  8. if(!$statement->execute()) {
  9. throw new Exception(implode(', ', $statement->errorInfo()));
  10. }
  11. $bounds = $statement->fetch(PDO::FETCH_ASSOC);
  12. $leftBound = $bounds['lft'];
  13. $rightBound = $bounds['rgt'];
  14. // delete the node and all its descendants
  15. $statement = $db->prepare("delete from list where lft >= $leftBound and rgt <= $rightBound");
  16. if(!$statement->execute()) {
  17. $db->rollBack();
  18. throw new Exception(implode(', ', $statement->errorInfo()));
  19. }
  20. // calculate the amount of empty space left after deleting the nodes.
  21. $emptySpace = $rightBound - $leftBound + 1;
  22. // decrement by the empty space amount the lft and rgt values for all nodes that come after the nodes that were deleted.
  23. $statement = $db->prepare("update list set lft = lft - $emptySpace where lft > $rightBound");
  24. if(!$statement->execute()) {
  25. $db->rollBack();
  26. throw new Exception(implode(', ', $statement->errorInfo()));
  27. }
  28. $statement = $db->prepare("update list set rgt = rgt - $emptySpace where rgt > $rightBound");
  29. if(!$statement->execute()) {
  30. $db->rollBack();
  31. throw new Exception(implode(', ', $statement->errorInfo()));
  32. }
  33. $jsonResult = array('success' => true);
  34. $db->commit();
  35. } catch(Exception $e) {
  36. $db->rollBack();
  37. $jsonResult = array(
  38. 'success' => false,
  39. 'message' => $e->getMessage()
  40. );
  41. }
  42. echo json_encode($jsonResult);
  43. ?>