PHP 体重管理网页 - 录入和图表展示
<!DOCTYPE html>
<html>
<head>
<title>体重管理</title>
<script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
<style>
canvas {
max-width: 100%;
height: auto;
}
</style>
</head>
<body>
<h1>体重管理</h1>
<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 ($_SERVER['REQUEST_METHOD'] == 'POST') {
$weight = $_POST['weight'];
$timestamp = time();
// 插入数据到数据库
$sql = "INSERT INTO tizhongrou (data, tizhong) VALUES ('$timestamp', '$weight')";
if ($conn->query($sql) === TRUE) {
echo '体重录入成功';
} else {
echo '错误: ' . $sql . '<br>' . $conn->error;
}
}
// 获取历史体重数据
$sql = "SELECT data, tizhong FROM tizhongrou";
$result = $conn->query($sql);
$dataPoints = array();
if ($result->num_rows > 0) {
while ($row = $result->fetch_assoc()) {
$dataPoints[] = array('x' => $row['data'], 'y' => $row['tizhong']);
}
}
// 关闭数据库连接
$conn->close();
?>
<!-- 体重录入表单 -->
<h2>录入体重</h2>
<form method="post" action="<?php echo $_SERVER['PHP_SELF']; ?>">
<label for="weight">体重(kg):</label>
<input type="number" step="0.01" name="weight" id="weight" required>
<input type="submit" value="提交">
</form>
<!-- 折线图 -->
<h2>历史体重趋势</h2>
<canvas id="weightChart"></canvas>
<script>
// 初始化折线图
var ctx = document.getElementById('weightChart').getContext('2d');
var weightChart = new Chart(ctx, {
type: 'line',
data: {
datasets: [{
label: '体重(kg)',
data: <?php echo json_encode($dataPoints); ?>,
borderColor: 'blue',
fill: false
}]
},
options: {
scales: {
x: {
type: 'time',
time: {
unit: 'day',
displayFormats: {
day: 'YYYY-MM-DD'
}
},
title: {
display: true,
text: '时间'
}
},
y: {
title: {
display: true,
text: '体重(kg)'
}
}
}
}
});
</script>
</code></pre>
</body>
</html>
原文地址: https://www.cveoy.top/t/topic/baLl 著作权归作者所有。请勿转载和采集!