PHP 体重管理系统 - 轻松记录你的体重变化
<!DOCTYPE html>
<html>
<head>
<title>PHP 体重管理系统</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
<h1>体重管理</h1>
<h2>录入体重</h2>
<form method="POST" action="">
<label for="weight">体重:</label>
<input type="number" step="0.1" name="weight" id="weight" required>
<input type="submit" name="submit" value="提交">
</form>
<h2>历史体重趋势</h2>
<canvas id="chart"></canvas>
<pre><code><?php
// 连接数据库
$servername = '103.214.173.233';
$username = 'water';
$password = 'xX300400';
$dbname = 'water';
$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn->connect_error) {
die('连接失败: ' . $conn->connect_error);
}
// 处理体重录入
if (isset($_POST['submit'])) {
$weight = $_POST['weight'];
$timestamp = time();
$sql = "INSERT INTO tizhongrou (data, tizhong) VALUES ('$timestamp', '$weight')";
if ($conn->query($sql) === TRUE) {
echo '体重录入成功!';
} else {
echo 'Error: ' . $sql . '<br>' . $conn->error;
}
}
// 获取历史体重数据
$sql = "SELECT data, tizhong FROM tizhongrou";
$result = $conn->query($sql);
$data = array();
while ($row = $result->fetch_assoc()) {
$data[] = array(
'data' => $row['data'],
'tizhong' => $row['tizhong']
);
}
// 关闭数据库连接
$conn->close();
?>
<script>
// 生成折线图
var ctx = document.getElementById('chart').getContext('2d');
var chartData = <?php echo json_encode($data); ?>;
var timestamps = [];
var weights = [];
chartData.forEach(function (item) {
timestamps.push(new Date(item.data * 1000));
weights.push(item.tizhong);
});
new Chart(ctx, {
type: 'line',
data: {
labels: timestamps,
datasets: [{
label: '体重',
data: weights,
borderColor: 'blue',
fill: false
}]
},
options: {
responsive: true,
scales: {
x: {
type: 'time',
time: {
unit: 'day'
}
},
y: {
beginAtZero: true,
suggestedMax: Math.max(...weights) + 5
}
}
}
});
</script>
</code></pre>
</body>
</html>
原文地址: http://www.cveoy.top/t/topic/baVN 著作权归作者所有。请勿转载和采集!