begin_transaction(); // Lock and read current max drg $rs = $con->query("SELECT COALESCE(MAX(drg), 0) AS maxdrg FROM details FOR UPDATE"); $row = $rs->fetch_assoc(); $next = (int)$row['maxdrg'] + 1; // Insert new details row with current timestamp $stmt = $con->prepare("INSERT INTO details (drg, enquiry_date) VALUES (?, NOW())"); $stmt->bind_param('i', $next); $stmt->execute(); // Ensure there is an addresses row so your dashboard JOIN shows it // If drg is the PK in addresses, this works without needing other fields $stmt2 = $con->prepare("INSERT INTO addresses (drg) VALUES (?) ON DUPLICATE KEY UPDATE drg = drg"); $stmt2->bind_param('i', $next); $stmt2->execute(); $con->commit(); // Send the user straight to the client brief header("Location: client-brief.php?drg={$next}"); exit; } catch (Throwable $e) { // Roll back and show a simple error if ($con->errno === 0) { // If we did not reach MySQL yet, nothing to roll back } else { @$con->rollback(); } http_response_code(500); echo "

Error creating enquiry

"; echo "
" . htmlspecialchars($e->getMessage(), ENT_QUOTES, 'UTF-8') . "
"; exit; }