/
functions.php
96 lines (66 loc) · 1.95 KB
/
functions.php
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
<?php
$json = json_decode(file_get_contents('php://input'));
$nickname = $json->userid;
$score = $json->score;
$query = insertIntoTable($nickname, $score);
if ($query != false){
echo "<p>Your High Score: " . $query . "</p>";
}
echo getTop10();
function insertIntoTable($userid, $currentScore) {
require('connect.php');
$sql = "SELECT highestscore FROM HighestScore
WHERE nickname = '" .$userid. "'";
$result = $connect->query($sql);
$hscore = $currentScore;
if ($result->num_rows == 0){
$sql = "INSERT INTO HighestScore(nickname, highestscore)
VALUES('" .$userid. "', " .$currentScore. ")";
if ($connect->query($sql) == TRUE){
return $hscore;
} else {
return false;
}
}
if ($result->num_rows == 1){
$hscore = $result->fetch_assoc()["highestscore"];
if ($hscore > $currentScore) {
return $hscore;
}
$hscore = $currentScore;
$sql = "UPDATE HighestScore
SET highestscore = " .$currentScore.
" WHERE nickname = '" .$userid. "'";
if ($connect->query($sql) == TRUE){
return $hscore;
} else {
return false;
}
}
if ($result->num_rows > 1){
echo "Error! Multiple users with the same nickname";
return false;
}
return $hscore;
}
function getTop10() {
require('connect.php');
$sql = "SELECT nickname, highestscore
FROM HighestScore
ORDER BY highestscore DESC
LIMIT 10";
$result = $connect->query($sql);
$rank = 1;
$value = "";
if ($result->num_rows > 0) {
$value = "<table><tr><th>Rank</th><th>User</th><th>Top 10 Scores</th></tr>";
while($row = $result->fetch_assoc()) {
$value .= "<tr><td>".$rank."</td><td>".$row["nickname"]."</td><td>".$row["highestscore"]."</td></tr>";
$rank++;
}
$value .= "</table>";
} else {
$value = "0 results";
}
return $value;
}