save-canvas.php 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. <?php
  2. /* Receives the email of the user, the name of the canvas and the date
  3. and stores it in the database with a randomly-generated canvas_id,
  4. that is returned. */
  5. session_start();
  6. $params = array();
  7. parse_str($_POST['save_canvas'], $params);
  8. if(!array_key_exists('email_save_canvas', $params) OR
  9. !array_key_exists('name_save_canvas', $params) OR
  10. !array_key_exists('date_save_canvas', $params)) {
  11. echo 400; // Missing parameters
  12. }
  13. else {
  14. if(isset($_SESSION['canvas_id'])) {
  15. // Canvas already exists. Return canvas_id to overwrite JSON file.
  16. echo $_SESSION['canvas_id'];
  17. }
  18. else { // New canvas in the database
  19. // Retrieve user credentials
  20. $email = $params['email_save_canvas'];
  21. $canvas_name = $params['name_save_canvas'];
  22. $date = $params['date_save_canvas'];
  23. $canvas_id = $params['id_save_canvas'];
  24. require_once('../../php/db_utils.php');
  25. $conn = db_connect(); // Connect to the database
  26. // Check if the username already exists
  27. if(!($result = mysqli_query($conn, "SELECT name FROM user WHERE username = '$email'"))) {
  28. echo 400; // Wrong query
  29. }
  30. else if(mysqli_num_rows($result) != 1) { // User not registered or duplicated
  31. echo 401;
  32. }
  33. else {
  34. // User registered
  35. // Save this canvas
  36. if(!mysqli_query($conn, "INSERT INTO canvas (canvas_id, user_id, canvas_name, canvas_date) VALUES ('$canvas_id', '$email', '$canvas_name', '$date')")) {
  37. echo 400; // Wrong query
  38. echo " #Wrong query :/ ";
  39. }
  40. else { // Return canvas_id and save it in the current session
  41. $_SESSION['canvas_id'] = $canvas_id;
  42. echo $canvas_id;
  43. }
  44. }
  45. }
  46. }
  47. ?>