Easiest way to upload score to a database/scoreboard?


#1

What would be the easiest way to upload players score to a database? I have established a connection to my database using php, but i have no idea how to get the score from my game to that php code.


#2

From within javascript you can use something like axios or the fetch api to send post requests to your server.


#3

when you create your game you pass it to the index.html page as a javascript script, so just rename the page index.php and start a section with <?php ... ?> and pass that data to it


#4

I ended up doing it like this:
First the JS code and later the php code:

function uploadScore(username, score) {
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (this.readyState == 4 && this.status == 200) {
            document.getElementById("test").innerHTML = this.responseText;
        }
    }
    request.open("GET", "uploadscore.php?user=" + username + "&score=" + score);
    request.setRequestHeader("Content-type", "application/json");
    request.send();
}




<?php 
    
    $user = $_REQUEST["user"];
    $score = $_REQUEST["score"];

    $servername = "localhost";
    $username = "user";
    $password = "pass";
    $dbname = "leaderboard";

    $conn = new mysqli($servername, $username, $password, $dbname);

    if(!$conn){
        die(" Connection Failed: " . mysqli_connect_error());
    }
    mysqli_select_db($conn,"highscores");
    $sql= "INSERT INTO `highscores`(`gamertag`, `score`) VALUES ('" . $user . "'," . $score . ")";
    if (mysqli_query($conn, $sql)) {
        echo " New record created successfully";
    } else {
        echo "Error: " . $sql . "<br>" . mysqli_error($conn);
    }

    mysqli_close($conn);

?>

#5

Expect some high scores :slight_smile: