File size: 1,735 Bytes
0270f27
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
```php
<?php
header('Content-Type: application/json');
header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST');
header('Access-Control-Allow-Headers: Content-Type');

$host = 'localhost';
$user = 'root';
$pass = '';
$db   = 'code_typing_game';

// Create connection
$conn = new mysqli($host, $user, $pass, $db);

// Check connection
if ($conn->connect_error) {
    die(json_encode(['success' => false, 'error' => 'Connection failed: ' . $conn->connect_error]));
}

// Handle POST request to save results
if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    $data = json_decode(file_get_contents('php://input'), true);
    
    $language = $conn->real_escape_string($data['language'] ?? '');
    $wpm = intval($data['wpm'] ?? 0);
    $accuracy = intval($data['accuracy'] ?? 0);
    $time = intval($data['time'] ?? 0);
    $timestamp = date('Y-m-d H:i:s');
    
    $sql = "INSERT INTO results (language, wpm, accuracy, time_taken, created_at) 
            VALUES ('$language', $wpm, $accuracy, $time, '$timestamp')";
    
    if ($conn->query($sql) === TRUE) {
        echo json_encode(['success' => true]);
    } else {
        echo json_encode(['success' => false, 'error' => $conn->error]);
    }
}

// Handle GET request to fetch leaderboard
if ($_SERVER['REQUEST_METHOD'] === 'GET') {
    $sql = "SELECT * FROM results ORDER BY wpm DESC LIMIT 10";
    $result = $conn->query($sql);
    
    $leaderboard = [];
    if ($result->num_rows > 0) {
        while($row = $result->fetch_assoc()) {
            $leaderboard[] = $row;
        }
    }
    
    echo json_encode(['success' => true, 'data' => $leaderboard]);
}

$conn->close();
?>
```

Now let's update the JavaScript to save results to the database: