-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdb.php
More file actions
89 lines (80 loc) · 2.3 KB
/
db.php
File metadata and controls
89 lines (80 loc) · 2.3 KB
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
<?php
function connectDB(){
$host = 'localhost';
$db = 'main';
$user = 'server';
$pass = 'P@ssw0rd';
$charset = 'utf8mb4';
$dsn = "mysql:host=$host;dbname=$db;charset=$charset";
$options = [
PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION,
PDO::ATTR_DEFAULT_FETCH_MODE => PDO::FETCH_ASSOC,
PDO::ATTR_EMULATE_PREPARES => false
];
return new PDO($dsn, $user, $pass, $options);
}
function tryLogin($uname, $passwd) {
try {
$dbh = connectDB();
$statement = $dbh->prepare("SELECT user, score FROM users WHERE user = :uname AND pass = sha2(:passwd,256)");
$statement->bindParam(":uname", $uname);
$statement->bindParam(":passwd", $passwd);
$statement->execute();
$result = $statement->fetch();
return $result;
} catch (PDOException $e) {
print "Error!" . $e->getMessage() . "<br/>";
die();
}
}
function newUser($uname, $passwd){
try{
$dbh = connectDB();
$statement = $dbh->prepare("INSERT INTO users (user, pass, score) VALUES (:uname, sha2(:passwd,256), 0)");
$statement->bindParam(":uname", $uname);
$statement->bindParam(":passwd", $passwd);
try { $statement->execute(); }
catch (Exception $e) {
echo '<script>alert("username in use");</script>';
die();
}
echo "<script>alert('account \"$uname\" registered! Now log in.');</script>";
} catch (PDOException $e) {
echo "Error: '". $e->getMessage() ."'";
}
}
function getScore($uname){
try {
$dbh = connectDB();
$statement = $dbh->prepare("SELECT score FROM users WHERE user = :uname");
$statement->bindParam(":uname", $uname);
$statement->execute();
return $statement->fetch()['score'];
} catch (PDOException $e) {
print "Error!" . $e->getMessage() . "<br/>";
die();
}
}
function upScore($uname): void{
try {
$dbh = connectDB();
$statement = $dbh->prepare("UPDATE users SET score = score + 1 WHERE user = :uname");
$statement->bindParam(":uname", $uname);
$statement->execute();
} catch (PDOException $e) {
print "Error!" . $e->getMessage() . "<br/>";
die();
}
}
function updateScore($uname,$score): void{
try {
$dbh = connectDB();
$statement = $dbh->prepare("UPDATE users SET score = $score WHERE user = :uname");
$statement->bindParam(":uname", $uname);
$statement->execute();
} catch (PDOException $e) {
print "Error!" . $e->getMessage() . "<br/>";
die();
}
}
?>