<!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>&lt;?php
// 连接数据库
$servername = '103.214.173.233';
$username = 'water';
$password = 'xX300400';
$dbname = 'water';

$conn = new mysqli($servername, $username, $password, $dbname);
if ($conn-&gt;connect_error) {
    die('连接失败: ' . $conn-&gt;connect_error);
}

// 处理体重录入
if (isset($_POST['submit'])) {
    $weight = $_POST['weight'];
    $timestamp = time();
    
    $sql = &quot;INSERT INTO tizhongrou (data, tizhong) VALUES ('$timestamp', '$weight')&quot;;
    
    if ($conn-&gt;query($sql) === TRUE) {
        echo '体重录入成功!';
    } else {
        echo 'Error: ' . $sql . '&lt;br&gt;' . $conn-&gt;error;
    }
}

// 获取历史体重数据
$sql = &quot;SELECT data, tizhong FROM tizhongrou&quot;;
$result = $conn-&gt;query($sql);
$data = array();
while ($row = $result-&gt;fetch_assoc()) {
    $data[] = array(
        'data' =&gt; $row['data'],
        'tizhong' =&gt; $row['tizhong']
    );
}

// 关闭数据库连接
$conn-&gt;close();
?&gt;

&lt;script&gt;
    // 生成折线图
    var ctx = document.getElementById('chart').getContext('2d');
    var chartData = &lt;?php echo json_encode($data); ?&gt;;
    
    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
                }
            }
        }
    });
&lt;/script&gt;
</code></pre>
</body>
</html>
PHP 体重管理系统 - 轻松记录你的体重变化

原文地址: http://www.cveoy.top/t/topic/baVN 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录