score ke database

This commit is contained in:
Daud 2025-12-05 12:50:38 +07:00
parent df3f478734
commit 77de57304e
2 changed files with 89 additions and 0 deletions

View File

@ -336,5 +336,35 @@
: speed; : speed;
}); });
} }
function updatedatabase(scoreBaru) {
// 1. Buat objek data yang akan dikirim
const KirimScore = {
action: 'SaveScore', // Identifier untuk PHP
score: scoreBaru
};
// 2. Gunakan Fetch API untuk mengirim permintaan POST
fetch('score.php', { // Ganti dengan nama file PHP Anda
method: 'POST',
headers: {
'Content-Type': 'application/json' // Beri tahu server bahwa yang dikirim adalah JSON
},
body: JSON.stringify(KirimScore) // Konversi data JS menjadi string JSON
})
.then(response => response.json()) // Ubah respons server kembali menjadi objek JS
.then(data => {
// 3. Tangani respons dari PHP
if (data.status === 'success') {
console.log('Score berhasil disimpan:', data.message);
// Lakukan sesuatu (misalnya: tampilkan pesan sukses di UI)
} else {
console.error('Gagal menyimpan score:', data.message);
}
})
.catch(error => {
console.error('Terjadi kesalahan koneksi:', error);
});
}
InputKeyboard(); InputKeyboard();
gameLoop(); gameLoop();

59
score.php Normal file
View File

@ -0,0 +1,59 @@
<?php
session_start();
header('Content-Type: application/json'); // Penting: Beri tahu klien bahwa respons adalah JSON
// --- 1. Koneksi Database (Ganti dengan detail Anda) ---
$host = 'localhost';
$db = 'nama_database_anda';
$user = 'user_db';
$pass = 'password_db';
$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,
];
try {
$pdo = new PDO($dsn, $user, $pass, $options);
} catch (\PDOException $e) {
http_response_code(500); // Internal Server Error
echo json_encode(['status' => 'error', 'message' => 'Gagal koneksi database.']);
exit;
}
// --- 2. Ambil Data dari JavaScript (AJAX) ---
$data = json_decode(file_get_contents('php://input'), true);
if (!isset($data['action']) || $data['action'] !== 'simpan_score') {
http_response_code(400); // Bad Request
echo json_encode(['status' => 'error', 'message' => 'Aksi tidak valid.']);
exit;
}
$score = filter_var($data['score'] ?? 0, FILTER_SANITIZE_NUMBER_INT);
$userId = 1; // Contoh: Asumsikan ID pengguna 1 (Anda harus mengambilnya dari sesi atau input)
if (!is_numeric($score) || $score < 0) {
http_response_code(400);
echo json_encode(['status' => 'error', 'message' => 'Score tidak valid.']);
exit;
}
// --- 3. Simpan ke Database (menggunakan Prepared Statements) ---
try {
$sql = "INSERT INTO scores (user_id, score, created_at) VALUES (?, ?, NOW())";
$stmt = $pdo->prepare($sql);
$stmt->execute([$userId, $score]);
// Berikan respons sukses ke JavaScript
echo json_encode(['status' => 'success', 'message' => 'Score berhasil disimpan.']);
} catch (\PDOException $e) {
http_response_code(500);
echo json_encode(['status' => 'error', 'message' => 'Gagal menyimpan score ke DB: ' . $e->getMessage()]);
}
?>