Spaces:
Running
Running
| ```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: |