base-saturation-pie.php 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. <?php
  2. /**
  3. * base-saturation-pie.php
  4. *
  5. * AJAX endpoint — returns base saturation percentages as JSON for pie chart.
  6. * Requires authentication.
  7. */
  8. require_once __DIR__ . '/../../../config/database.php';
  9. require_once __DIR__ . '/../../../lib/auth.php';
  10. if (session_status() === PHP_SESSION_NONE) {
  11. session_start();
  12. }
  13. if (!isLoggedIn()) {
  14. http_response_code(401);
  15. echo json_encode(['error' => 'Unauthorised']);
  16. exit;
  17. }
  18. $record_id = (int) ($_GET['rid'] ?? 0);
  19. $rand_id = (float)($_GET['rand'] ?? 0);
  20. if (!$record_id || !$rand_id) {
  21. http_response_code(400);
  22. echo json_encode(['error' => 'Invalid parameters']);
  23. exit;
  24. }
  25. try {
  26. $pdo = getDBConnection();
  27. $stmt = $pdo->prepare(
  28. 'SELECT BS_ca2, BS_mg2, BS_k, BS_na, BS_ob, BS_h
  29. FROM `soil_records`
  30. WHERE id = ? AND rand = ?
  31. LIMIT 1'
  32. );
  33. $stmt->execute([$record_id, $rand_id]);
  34. $row = $stmt->fetch();
  35. header('Content-Type: application/json');
  36. if (!$row) {
  37. http_response_code(404);
  38. echo json_encode(['error' => 'Record not found']);
  39. exit;
  40. }
  41. echo json_encode([$row]);
  42. } catch (PDOException $e) {
  43. error_log('base-saturation-pie.php DB error: ' . $e->getMessage());
  44. http_response_code(500);
  45. echo json_encode(['error' => 'Database error']);
  46. }