create_enquiry.php 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748
  1. <?php
  2. // create_enquiry.php
  3. declare(strict_types=1);
  4. date_default_timezone_set('Australia/Hobart');
  5. require_once 'connection.php';
  6. // Throw exceptions on SQL errors for clean handling
  7. mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
  8. try {
  9. // Start a transaction to avoid two users getting the same number
  10. $con->begin_transaction();
  11. // Lock and read current max drg
  12. $rs = $con->query("SELECT COALESCE(MAX(drg), 0) AS maxdrg FROM details FOR UPDATE");
  13. $row = $rs->fetch_assoc();
  14. $next = (int)$row['maxdrg'] + 1;
  15. // Insert new details row with current timestamp
  16. $stmt = $con->prepare("INSERT INTO details (drg, enquiry_date) VALUES (?, NOW())");
  17. $stmt->bind_param('i', $next);
  18. $stmt->execute();
  19. // Ensure there is an addresses row so your dashboard JOIN shows it
  20. // If drg is the PK in addresses, this works without needing other fields
  21. $stmt2 = $con->prepare("INSERT INTO addresses (drg) VALUES (?) ON DUPLICATE KEY UPDATE drg = drg");
  22. $stmt2->bind_param('i', $next);
  23. $stmt2->execute();
  24. $con->commit();
  25. // Send the user straight to the client brief
  26. header("Location: client-brief.php?drg={$next}");
  27. exit;
  28. } catch (Throwable $e) {
  29. // Roll back and show a simple error
  30. if ($con->errno === 0) {
  31. // If we did not reach MySQL yet, nothing to roll back
  32. } else {
  33. @$con->rollback();
  34. }
  35. http_response_code(500);
  36. echo "<h1>Error creating enquiry</h1>";
  37. echo "<pre>" . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . "</pre>";
  38. exit;
  39. }