create.php 2.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374
  1. <?php
  2. include '../connection.php';
  3. try {
  4. $params = json_decode(file_get_contents('php://input'));
  5. unset($params->id);
  6. $db->beginTransaction();
  7. if($params->parentId > 0) {
  8. // find the list's parent node
  9. $statement = $db->prepare("select * from list where id = $params->parentId");
  10. if($statement->execute()) {
  11. $parent = $statement->fetch(PDO::FETCH_ASSOC);
  12. if(!$parent) {
  13. throw new Exception('parent node could not be found');
  14. }
  15. } else {
  16. throw new Exception(implode(', ', $statement->errorInfo()));
  17. }
  18. // the left bound of the new node is it's parent's right bound (append node to end of parent's child nodes)
  19. $leftBound = $parent['rgt'];
  20. // the right bound of the new node is leftBound + 1, because the new node has no children
  21. $rightBound = $leftBound + 1;
  22. // before we can insert a new node we need to increment by 2 the left and right values for all nodes to the right of where the new node is being inserted
  23. $statement = $db->prepare("update list set lft = lft + 2 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 + 2 where rgt >= $leftBound");
  29. if(!$statement->execute()) {
  30. $db->rollBack();
  31. throw new Exception(implode(', ', $statement->errorInfo()));
  32. }
  33. } else {
  34. // if there is no parent, append the new node as a root node at the very end
  35. $statement = $db->prepare('select max(rgt) from list');
  36. if($statement->execute()) {
  37. // the left bound of the new node is right after the right bound of the node with the highest right bound in the table
  38. $leftBound = $statement->fetch(PDO::FETCH_COLUMN) + 1;
  39. // the right bound of the new node is leftBound + 1, because the new node has no children
  40. $rightBound = $leftBound + 1;
  41. } else {
  42. throw new Exception(implode(', ', $statement->errorInfo()));
  43. }
  44. }
  45. // insert the new list node into the database
  46. $statement = $db->prepare("insert into list (name, leaf, lft, rgt) values('$params->name', " . intval($params->leaf) . ", $leftBound, $rightBound)");
  47. if(!$statement->execute()) {
  48. $db->rollBack();
  49. throw new Exception(implode(', ', $statement->errorInfo()));
  50. }
  51. $params->id = $db->lastInsertId();
  52. $jsonResult = array(
  53. 'success' => true,
  54. 'children' => (array)$params
  55. );
  56. $db->commit();
  57. } catch(Exception $e) {
  58. $db->rollBack();
  59. $jsonResult = array(
  60. 'success' => false,
  61. 'message' => $e->getMessage()
  62. );
  63. }
  64. echo json_encode($jsonResult);
  65. ?>