Simple Leaderboard Tutorial in PHP & JS

This blog post is brought to you by the developer of BitBudget. BitBudget is an automated budgeting app for Android and iOS which syncs with your bank account and helps you avoid overspending. If you’d like to quit living paycheck-to-paycheck and get a better handle on your finances, download it today! https://bitbudget.io

Quick little tutorial on creating a leaderboard for a PhaserJS game with PHP and a little JS =>

// Guys, we need to write a little javascript here
// to add the user's score to our database
var playerName = "nUb";
var score = points;
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
// document.getElementById("demo").innerHTML = this.responseText;
alert(this.responseText);
}
};
xhttp.open("POST", "add_score_to_leaderboard.php", true);
var myFormData = new FormData();
myFormData.append("playerName", playerName);
myFormData.append("score", score);
xhttp.send(myFormData);
<?php
$playerName = $_POST['playerName'];
$score = $_POST["score"];
$servername = "localhost";
$username = "shranos_admin";
$password = "letsgo";
$dbname = "shranos_db";
// Create connection
$conn = new mysqli($servername,$username,$password,$dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: ".$conn->connect_error);
}
// $sql = "INSERT INTO leaderboard_table (username_column, highscore_column) VALUES ('aNub', 0)";
$sql = "INSERT INTO leaderboard_table (username_column, highscore_column) VALUES ('" . $playerName . "', " . $score . ")";
if ($conn->query($sql)===TRUE) {
// echo "New record created successfully";
echo "your moms score added to leaderboard, thx noob";
} else {
// echo "Error: ".$sql."<br>".$conn_error;
echo "ERROR: PC LOAD LETTER";
}
$conn->close();
?>
 

topherPedersen