浏览代码

First Test

Thomas Buck 5 年前
父节点
当前提交
64051cfbec
共有 5 个文件被更改,包括 491 次插入9 次删除
  1. 2
    0
      .gitignore
  2. 8
    0
      config.example.php
  3. 225
    0
      index.html
  4. 0
    9
      index.php
  5. 256
    0
      weight.php

+ 2
- 0
.gitignore 查看文件

@@ -0,0 +1,2 @@
1
+.DS_Store
2
+config.php

+ 8
- 0
config.example.php 查看文件

@@ -0,0 +1,8 @@
1
+<?php
2
+
3
+$sql_host = 'localhost';
4
+$sql_username = 'root';
5
+$sql_password = '';
6
+$sql_database = 'weight-test';
7
+
8
+?>

+ 225
- 0
index.html 查看文件

@@ -0,0 +1,225 @@
1
+<html lang="en">
2
+    <head>
3
+        <meta charset="utf-8" />
4
+        <title>Weight-Track</title>
5
+        <script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.7.3/Chart.bundle.min.js" integrity="sha256-MZo5XY1Ah7Z2Aui4/alkfeiq3CopMdV/bbkc/Sh41+s=" crossorigin="anonymous"></script>
6
+    </head>
7
+    <body>
8
+        <div id="content">
9
+            <h1>Weight-Track</h1>
10
+            <p id="status">Please wait while Weight-Track is loading... (JavaScript needed)</p>
11
+        </div>
12
+        <div id="footer">
13
+            <p>Made with <a href="https://www.chartjs.org/docs/latest/">Chart.js</a></p>
14
+        </div>
15
+        <script type="text/javascript">
16
+            var colorFromIndex = function(index) {
17
+                var colors = [
18
+                    '255, 99, 132',
19
+                    '54, 162, 235',
20
+                    '255, 206, 86',
21
+                    '75, 192, 192',
22
+                    '153, 102, 255',
23
+                    '255, 159, 64'
24
+                ];
25
+                if (index < colors.length) {
26
+                    return colors[index];
27
+                } else {
28
+                    return '120, 120, 120';
29
+                }
30
+            };
31
+
32
+            var createDataset = function(name, data, color) {
33
+                return {
34
+                    label: name,
35
+                    data: data,
36
+                    backgroundColor: [
37
+                        'rgba(' + color + ', 0)'
38
+                    ],
39
+                    borderColor: [
40
+                        'rgba(' + color + ', 1)'
41
+                    ],
42
+                    borderWidth: 4
43
+                };
44
+            };
45
+
46
+            var addToForm = function(form, element, name) {
47
+                var fe = document.createElement('p');
48
+                fe.innerHTML = name + ' ';
49
+                fe.appendChild(element);
50
+                form.appendChild(fe);
51
+            };
52
+
53
+            var renderUser = function(data) {
54
+                var div = document.createElement('div');
55
+                var ctx = document.createElement('canvas');
56
+
57
+                var datasets = [];
58
+                for (var i = 0; i < data.users.length; i++) {
59
+                    var set = createDataset(data.users[i].name,
60
+                            data.users[i].data, colorFromIndex(i));
61
+                    datasets.push(set);
62
+                }
63
+
64
+                var chart = new Chart(ctx, {
65
+                    type: 'line',
66
+                    data: {
67
+                        datasets: datasets
68
+                    },
69
+                    options: {
70
+                        scales: {
71
+                            xAxes: [{
72
+                                type: 'time',
73
+                                time: {
74
+                                    unit: 'day'
75
+                                }
76
+                            }]
77
+                        },
78
+                        events: [
79
+                            'mousemove', 'mouseout', 'click',
80
+                            'touchstart', 'touchmove', 'touchend'
81
+                        ],
82
+                        tooltips: {
83
+                            mode: 'nearest',
84
+                            intersect: false,
85
+                            axis: 'x'
86
+                        }
87
+                    }
88
+                });
89
+
90
+                if (data.users.length > 0) {
91
+                    div.appendChild(ctx);
92
+                    div.appendChild(document.createElement('hr'));
93
+
94
+                    var date = new Date();
95
+                    var hours = date.getHours();
96
+                    hours = (hours < 10) ? '0' + hours : hours;
97
+                    var minutes = date.getMinutes();
98
+                    minutes = (minutes < 10) ? '0' + minutes : minutes;
99
+
100
+                    var form_append = document.createElement('form');
101
+                    form_append.setAttribute('method', 'post');
102
+                    form_append.setAttribute('action', 'weight.php');
103
+
104
+                    var p_append = document.createElement('p');
105
+                    p_append.innerHTML = 'Add new Data-Point:';
106
+                    form_append.appendChild(p_append);
107
+
108
+                    var name_append = document.createElement('select');
109
+                    for (var i = 0; i < data.users.length; i++) {
110
+                        var option = document.createElement('option');
111
+                        option.text = data.users[i].name;
112
+                        option.value = 'user_' + data.users[i].id;
113
+                        name_append.add(option);
114
+                    }
115
+                    name_append.setAttribute('name', 'username');
116
+                    name_append.required = true;
117
+                    addToForm(form_append, name_append, 'Username:');
118
+
119
+                    var date_append = document.createElement('input');
120
+                    date_append.setAttribute('type', 'date');
121
+                    date_append.setAttribute('name', 'date');
122
+                    date_append.setAttribute('placeholder', 'Date');
123
+                    date_append.required = true;
124
+                    date_append.value = date.toISOString().slice(0, 10);
125
+                    addToForm(form_append, date_append, 'Date:');
126
+
127
+                    var time_append = document.createElement('input');
128
+                    time_append.setAttribute('type', 'time');
129
+                    time_append.setAttribute('name', 'time');
130
+                    time_append.setAttribute('placeholder', 'Time');
131
+                    time_append.required = true;
132
+                    time_append.value = hours + ':' + minutes;
133
+                    addToForm(form_append, time_append, 'Time:');
134
+
135
+                    var weight_append = document.createElement('input');
136
+                    weight_append.setAttribute('type', 'number');
137
+                    weight_append.setAttribute('name', 'weight');
138
+                    weight_append.setAttribute('step', '0.1');
139
+                    weight_append.setAttribute('placeholder', 'Weight');
140
+                    weight_append.required = true;
141
+                    addToForm(form_append, weight_append, 'Weight:');
142
+
143
+                    var submit_append = document.createElement('input');
144
+                    submit_append.setAttribute('type', 'submit');
145
+                    submit_append.setAttribute('value', 'Add Data');
146
+                    form_append.appendChild(submit_append);
147
+
148
+                    div.appendChild(form_append);
149
+                    div.appendChild(document.createElement('hr'));
150
+                }
151
+
152
+                var form_new = document.createElement('form');
153
+                form_new.setAttribute('method', 'post');
154
+                form_new.setAttribute('action', 'weight.php');
155
+
156
+                var p_new = document.createElement('p');
157
+                p_new.innerHTML = 'Add new User:';
158
+                form_new.appendChild(p_new);
159
+
160
+                var name_new = document.createElement('input');
161
+                name_new.setAttribute('type', 'text');
162
+                name_new.setAttribute('name', 'username');
163
+                name_new.setAttribute('placeholder', 'Name');
164
+                name_new.required = true;
165
+                addToForm(form_new, name_new, 'Username:');
166
+
167
+                var submit_new = document.createElement('input');
168
+                submit_new.setAttribute('type', 'submit');
169
+                submit_new.setAttribute('value', 'Add User');
170
+                form_new.appendChild(submit_new);
171
+
172
+                div.appendChild(form_new);
173
+                div.appendChild(document.createElement('hr'));
174
+                document.getElementById("content").appendChild(div);
175
+            };
176
+
177
+            var getJSON = function(url, callback) {
178
+                var xhr = new XMLHttpRequest();
179
+                xhr.open('GET', url, true);
180
+                xhr.responseType = 'json';
181
+                xhr.onload = function() {
182
+                    if (xhr.status === 200) {
183
+                        callback(null, xhr.response);
184
+                    } else {
185
+                        callback(xhr.status, xhr.response);
186
+                    }
187
+                };
188
+                xhr.send();
189
+            };
190
+
191
+            document.getElementById("status").textContent = "Loading from Database...";
192
+
193
+            getJSON('weight.php', function(err, data) {
194
+                if (err !== null) {
195
+                    document.getElementById("status").textContent = 'Error: ' + err;
196
+                    return;
197
+                }
198
+                if (typeof data.error !== 'undefined') {
199
+                    document.getElementById("status").textContent = 'Error: ' + data.error;
200
+                    return;
201
+                }
202
+                if (typeof data.users !== 'undefined') {
203
+                    var s = 'Received data for ' + data.users.length + ' users';
204
+                    if (data.users.length > 0) {
205
+                        s += ': ';
206
+                        for (var i = 0; i < data.users.length; i++) {
207
+                            s += '"' + data.users[i].name + '"';
208
+                            if (i < (data.users.length - 1)) {
209
+                                s += ', ';
210
+                            }
211
+                        }
212
+                        s += '. Rendering...';
213
+                    } else {
214
+                        s += '. Nothing to show!';
215
+                    }
216
+                    document.getElementById("status").textContent = s;
217
+                    renderUser(data);
218
+                } else {
219
+                    document.getElementById("status").textContent = 'Error: no data';
220
+                    return;
221
+                }
222
+            });
223
+        </script>
224
+    </body>
225
+</html>

+ 0
- 9
index.php 查看文件

@@ -1,9 +0,0 @@
1
-<html>
2
-    <head>
3
-        <title>Weight-Track</title>
4
-    </head>
5
-    <body>
6
-        <h1>Hello World</h1>
7
-    </body>
8
-</html>
9
-

+ 256
- 0
weight.php 查看文件

@@ -0,0 +1,256 @@
1
+<?php
2
+
3
+/*
4
+ * When calleld as is, return JSON object like this:
5
+ * {
6
+ *   "users": [
7
+ *     {
8
+ *       "name": "User 1",
9
+ *       "id": 0,
10
+ *       "data": [
11
+ *         {
12
+ *           "x": "2018-10-29 20:30",
13
+ *           "y": "110.0"
14
+ *         },
15
+ *         {
16
+ *           "x": "2018-10-30 20:30",
17
+ *           "y": "110.5"
18
+ *         }
19
+ *       ]
20
+ *     },
21
+ *     {
22
+ *       "name": "User 2",
23
+ *       "id": 1,
24
+ *       "data": [
25
+ *         {
26
+ *           "x": "2018-10-29 20:30",
27
+ *           "y": "105.5"
28
+ *         },
29
+ *         {
30
+ *           "x": "2018-10-30 20:30",
31
+ *           "y": "105.0"
32
+ *         }
33
+ *       ]
34
+ *     }
35
+ *   ]
36
+ * }
37
+ * or
38
+ * {
39
+ *   "error": "No configuration found"
40
+ * }
41
+ *
42
+ * When called with POST parameters, add user or data-point to db
43
+ * parameters: username, (date, time, weight)
44
+ */
45
+
46
+function print_json_error($s) {
47
+    echo '{';
48
+    echo '  "error": "' . $s;
49
+    if (mysql_errno()) {
50
+        echo ' (' . mysql_error() . ')';
51
+    }
52
+    echo '"';
53
+    echo '}';
54
+}
55
+
56
+function print_html($s) {
57
+    echo '<html lang="en">';
58
+    echo '    <head>';
59
+    echo '        <meta charset="utf-8" />';
60
+    echo '        <title>Weight-Track DB</title>';
61
+    echo '    </head>';
62
+    echo '    <body>';
63
+    echo '        <p>' . $s . '</p>';
64
+    if (mysql_errno()) {
65
+        echo '<p>MySQL Error: "' . mysql_error() . '"</p>';
66
+    }
67
+    echo '        <a href="index.html">Back to Main-Page...</a>';
68
+    echo '    </body>';
69
+    echo '</html>';
70
+}
71
+
72
+function print_error($s) {
73
+    if (isset($_POST['username'])) {
74
+        return print_html($s);
75
+    } else {
76
+        return print_json_error($s);
77
+    }
78
+}
79
+
80
+include('config.php');
81
+
82
+if ((!isset($sql_host))
83
+        || (!isset($sql_username))
84
+        || (!isset($sql_password))
85
+        || (!isset($sql_database))) {
86
+    print_error('Configuration Error');
87
+    exit(1);
88
+}
89
+
90
+$db = mysql_connect($sql_host, $sql_username, $sql_password);
91
+mysql_select_db($sql_database);
92
+if (mysql_errno()) {
93
+    print_error('Database Error');
94
+    exit(1);
95
+}
96
+
97
+$sql = 'CREATE TABLE IF NOT EXISTS weight_users (';
98
+$sql .= 'id int NOT NULL AUTO_INCREMENT,';
99
+$sql .= 'name varchar(255),';
100
+$sql .= 'PRIMARY KEY (id)';
101
+$sql .= ');';
102
+$result = mysql_query($sql);
103
+if (!$result) {
104
+    print_error('Error (re-) creating database table for users!');
105
+    exit(1);
106
+}
107
+
108
+$sql = 'CREATE TABLE IF NOT EXISTS weight_data (';
109
+$sql .= 'id int NOT NULL,';
110
+$sql .= 'date DATETIME,';
111
+$sql .= 'weight DECIMAL(5,2)';
112
+$sql .= ');';
113
+$result = mysql_query($sql);
114
+if (!$result) {
115
+    print_error('Error (re-) creating database table for weights!');
116
+    exit(1);
117
+}
118
+
119
+if (isset($_POST['username'])
120
+        && isset($_POST['date'])
121
+        && isset($_POST['time'])
122
+        && isset($_POST['weight'])) {
123
+    $sql = 'INSERT INTO weight_data(id, date, weight) VALUES (';
124
+    $sql .= mysql_real_escape_string(str_replace('user_', '', $_POST['username']));
125
+    $sql .= ', ';
126
+
127
+    $datetime = $_POST['date'] . $_POST['time'];
128
+    $timestamp = strtotime($datetime);
129
+    if (($timestamp == FALSE) || ($timestamp == -1)) {
130
+        print_error('Error interpreting DateTime: "' . $datetime . '"');
131
+        exit(1);
132
+    }
133
+    $mysqltime = date("Y-m-d H:i:s", $timestamp);
134
+    $sql .= '"' . $mysqltime . '", ';
135
+
136
+    $sql .= mysql_real_escape_string($_POST['weight']) . ')';
137
+
138
+    $result = mysql_query($sql);
139
+    if (!$result) {
140
+        print_error('Error adding new data for user "' . $_POST['username'] . '" to DB! ' . $sql);
141
+    } else {
142
+        print_error('Added new data for user "' . $_POST['username'] . '" to DB!');
143
+    }
144
+} else if (isset($_POST['username'])) {
145
+    $sql = 'INSERT INTO weight_users(name) VALUES ("';
146
+    $sql .= mysql_real_escape_string($_POST['username']);
147
+    $sql .= '")';
148
+    $result = mysql_query($sql);
149
+    if (!$result) {
150
+        print_error('Error adding new user "' . $_POST['username'] . '" to DB!');
151
+    } else {
152
+        print_error('Added new user "' . $_POST['username'] . '" to DB!');
153
+    }
154
+} else if (isset($_GET['debug'])) {
155
+    echo <<<EOF
156
+{
157
+  "users": [
158
+    {
159
+      "name": "User 1",
160
+      "id": 0,
161
+      "data": [
162
+        {
163
+          "x": "2018-10-27 20:30",
164
+          "y": "110.0"
165
+        },
166
+        {
167
+          "x": "2018-10-28 20:30",
168
+          "y": "110.7"
169
+        },
170
+        {
171
+          "x": "2018-10-29 20:30",
172
+          "y": "110.2"
173
+        },
174
+        {
175
+          "x": "2018-10-30 20:30",
176
+          "y": "111.8"
177
+        }
178
+      ]
179
+    },
180
+    {
181
+      "name": "User 2",
182
+      "id": 1,
183
+      "data": [
184
+        {
185
+          "x": "2018-10-27 20:30",
186
+          "y": "103.5"
187
+        },
188
+        {
189
+          "x": "2018-10-28 20:30",
190
+          "y": "105.0"
191
+        },
192
+        {
193
+          "x": "2018-10-29 20:30",
194
+          "y": "105.5"
195
+        },
196
+        {
197
+          "x": "2018-10-30 20:30",
198
+          "y": "104.0"
199
+        }
200
+      ]
201
+    }
202
+  ]
203
+}
204
+EOF;
205
+} else {
206
+    $sql = 'SELECT id, name FROM weight_users ORDER BY id ASC';
207
+    $result = mysql_query($sql);
208
+    if (!$result) {
209
+        print_error('Error fetching users from database!');
210
+        exit(1);
211
+    }
212
+    $data = array();
213
+    while ($row = mysql_fetch_array($result)) {
214
+        $sql2 = 'SELECT date, weight FROM weight_data ';
215
+        $sql2 .= 'WHERE id = "' . $row['id'] . '" ORDER BY date ASC';
216
+        $result2 = mysql_query($sql2);
217
+        if (!$result2) {
218
+            print_error('Error fetching data for user ' . $row['id'] . ' "' . $row['name'] . '"!');
219
+            exit(1);
220
+        }
221
+        $cur = array();
222
+        $cur['name'] = $row['name'];
223
+        $cur['id'] = $row['id'];
224
+        $cur['data'] = array();
225
+        while ($row2 = mysql_fetch_array($result2)) {
226
+            $elem = array();
227
+            $elem['date'] = $row2['date'];
228
+            $elem['weight'] = $row2['weight'];
229
+            $cur['data'][] = $elem;
230
+        }
231
+        $data[] = $cur;
232
+    }
233
+    echo '{"users": [';
234
+    foreach ($data as $data_key => $data_value) {
235
+        if ($data_key > 0) {
236
+            echo ',';
237
+        }
238
+        echo '{';
239
+        echo '"name": "' . $data_value['name'] . '",';
240
+        echo '"id": ' . $data_value['id'] . ',';
241
+        echo '"data": [';
242
+        foreach ($data_value['data'] as $row_key => $row_value) {
243
+            if ($row_key > 0) {
244
+                echo ',';
245
+            }
246
+            echo '{';
247
+            echo '"x": "' . $row_value['date'] . '",';
248
+            echo '"y": "' . $row_value['weight'] . '"';
249
+            echo '}';
250
+        }
251
+        echo ']}';
252
+    }
253
+    echo ']}';
254
+}
255
+
256
+?>

正在加载...
取消
保存