0) { $stmt = $pdo->prepare('SELECT id FROM client_records WHERE id = ? AND modx_user_id = ?'); $stmt->execute([$clientId, $userId]); if (!$stmt->fetch()) { $clientId = 0; } } $rand = mt_rand(10000, 99999); $fields = [ 'lab_no', 'batch_no', 'date_sampled', 'sample_id', 'site_id', 'ph', 'cond_dsm', 'hco3', 'n', 'p', 'k', 's', 'mg', 'ca', 'na', 'fe', 'mn', 'zn', 'cu', 'b', 'm', 'co', 'se', 'ch', ]; $colList = 'modx_user_id, client_records_id, rand, ' . implode(', ', array_map(fn($c) => "`$c`", $fields)); $placeholders = implode(', ', array_fill(0, count($fields) + 3, '?')); $values = [$userId, $clientId ?: null, $rand]; foreach ($fields as $field) { $val = trim((string) ($_POST[$field] ?? '')); $values[] = ($val === '') ? null : $val; } try { $stmt = $pdo->prepare("INSERT INTO water_records ($colList) VALUES ($placeholders)"); $stmt->execute($values); $newId = (int) $pdo->lastInsertId(); $_SESSION['flash_success'] = 'Water test record saved successfully.'; header("Location: /dashboard/inbox.php"); } catch (\PDOException $e) { $_SESSION['flash_error'] = 'Failed to save record. Please try again.'; header('Location: /dashboard/crop-analysis/water-test-data/water-test-data.php'); } exit;