38671-vm/api/weight.php
2026-02-21 16:37:23 +00:00

29 lines
1.0 KiB
PHP

<?php
header('Content-Type: application/json');
require_once __DIR__ . '/../db/config.php';
$pdo = db();
$method = $_SERVER['REQUEST_METHOD'];
if ($method === 'POST') {
$input = json_decode(file_get_contents('php://input'), true);
$weight = filter_var($input['weight'] ?? 0, FILTER_VALIDATE_FLOAT);
$date = $input['date'] ?? date('Y-m-d');
if ($weight <= 0) {
echo json_encode(['success' => false, 'error' => 'Invalid weight']);
exit;
}
try {
$stmt = $pdo->prepare("INSERT INTO weight_logs (weight, logged_at) VALUES (?, ?) ON DUPLICATE KEY UPDATE weight = VALUES(weight)");
$stmt->execute([$weight, $date]);
echo json_encode(['success' => true]);
} catch (PDOException $e) {
echo json_encode(['success' => false, 'error' => $e->getMessage()]);
}
} elseif ($method === 'GET') {
$stmt = $pdo->query("SELECT weight, logged_at FROM weight_logs ORDER BY logged_at DESC LIMIT 30");
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
}