Need help on Custom DataStore HTTPService and MySQL

Hey, I want to have my own DataStore in MySQL.
I already have my MySQL Database working with a PHP script that can Read or Add Rows into the Table.

The problem is that I don’t know how to interact with it by using Roblox… Some people told me to use HTTPService , but what exactly will be sent to my PHP page?

This is my current Roblox Script :


local HttpService = game:GetService("HttpService")

game.Players.PlayerAdded:Connect(function(player)
	local playerUserId = "Player_" .. player.UserId
	local success = pcall(function()
		HttpService:PostAsync("Website", "PlayerID="..playerUserId)
	end)
	if not success then
		print("The Remote server could not be accessed.")
	else
		print("Sent "..playerUserId.." to Database")
	end
end)

This is my PHP Script

<?php
$servername = "localhost";
$username = "xxxx";
$password = "xxxx";
$dbname = "xxxx";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

$PlayerID = $_POST['PlayerID'];
if($PlayerID != NULL){
	$sql = "INSERT INTO Players (PlayerID, Score1, Score2)
VALUES ('$PlayerID', '0', '0')";
}

$sql = "SELECT * FROM Players";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
  // output data of each row
  while($row = mysqli_fetch_assoc($result)) {
    echo "id: " . $row["PlayerID"]. "<br>Score1: " . $row["Score1"] . "<br>";
  }
} else {
  echo "0 results";
}
?>

I see the message " Sent Player_1874241968 to Database " in the Roblox console, but nothing as been added into my Database :confused:

1 Like

the domain ‘robloxdb.000webhostapp.com’ is owned by you??

yeah, Its the link my Free Webhost gave me.

try changing to

local HttpService = game:GetService("HttpService")

game.Players.PlayerAdded:Connect(function(player)
	local playerUserId = "Player_" .. player.UserId
	local success = pcall(function()
		print(HttpService:PostAsync("Website", "PlayerID="..playerUserId))
	end)
	if not success then
		print("The Remote server could not be accessed.")
	else
		print("Sent "..playerUserId.." to Database")
	end
end)

this code should print php error

Correct me if I’m wrong but the MySQL database you get with 000webhost runs on its own separate server, not localhost (which would be your website’s server)? Double check your SQL connection details.

I’d also recommend securing your web server with some form of authentication, e.g. an API key. There’s nothing stopping me making a POST request to update your database.

Thanks dollychun ,

Now I have this PHP error

[<b>Notice</b>: Undefined index: PlayerID in <b>/storage/ssd4/191/15032191/public_html/index.php</b> on line <b>18</b><br />]

I was trying to get the data with a _POST
Should I use something else ?

$PlayerID = $_POST['PlayerID'];

You should be sending a JSON-encoded payload to your server script from Roblox using JSONEncode. If you’re using Php, you must get the raw input like this

$payload = json_decode(file_get_contents("php://input"), true);

You can then access it like an array in Php.

I’m fluent in Python/Django, JS/Node, and Php. Hopefully I can be of some help.

Spell miss.

file_get_contentrs

Okay Great !! Thanks, It super Useful to know :smiley:

Now this is my Roblox Script :

local HttpService = game:GetService("HttpService")

game.Players.PlayerAdded:Connect(function(player)
	local playerUserId = "Player_" .. player.UserId
	
	local Data = {
		["PlayerID"] = playerUserId;
	}
	Data = HttpService:JSONEncode(Data)
	
	local success = pcall(function()
		print(HttpService:PostAsync("WebPage", Data))
	end)
	if not success then
		print("The Remote server could not be accessed.")
	else
		print("Sent "..playerUserId.." to Database")
	end
end)

But how do I extract my PlayerID from the $Payload variable?

$payload = json_decode(file_get_contents("php://input"), true);

I tried to find more info about that on internet, but I could not find a proper example.

$payload is an array.

$payload['PlayerID'];

I’ve used 000webhost for php before and it is localhost.

Okay thanks MrNicNac,
sadly my Database is still Empty. I’m probably still doing something wrong.
But I have no more PHP error when i’m launching my Roblox game.

Roblox Script :

local HttpService = game:GetService("HttpService")
game.Players.PlayerAdded:Connect(function(player)
	local playerUserId = "Player_" .. player.UserId
	local Data = {
		["PlayerID"] = playerUserId;
	}
	Data = HttpService:JSONEncode(Data)
	local success = pcall(function()
		print(HttpService:PostAsync("WebPage", Data))
	end)
	if not success then
		print("The Remote server could not be accessed.")
	else
		print("Sent "..playerUserId.." to Database")
	end
end)  

PHP page :

<?php
$servername = "localhost";
$username = "username ";
$password = "password";
$dbname = "dbname ";

$conn = mysqli_connect($servername, $username, $password, $dbname);
if (!$conn) {
  die("Connection failed: " . mysqli_connect_error());
}

$payload = json_decode(file_get_contents("php://input"), true);
$PlayerID = $payload['PlayerID'];

if($PlayerID != NULL){
	$sql = "INSERT INTO Players (PlayerID, Score1, Score2)
VALUES ('$PlayerID', '0', '0')";
}

$sql = "SELECT * FROM Players";
$result = mysqli_query($conn, $sql);

if (mysqli_num_rows($result) > 0) {
  // output data of each row
  while($row = mysqli_fetch_assoc($result)) {
    echo "id: " . $row["PlayerID"]. "<br>Score1: " . $row["Score1"] . "<br>";
  }
} else {
  echo "0 results";
}
?>

Well, unfortunately I’m not magic and can’t just know the issue by staring at the script. We’ll need some output data about what is happening.

PostAsync returns the response from the server (Php) language. You should be capturing this, which it seems you are. Does it just tell you 0 results?

Starting here in your Php script

if($PlayerID != NULL){

Things just start to get a bit… wonky. Try doing this approach instead.

<?php

$servername = "localhost";
$username = "username ";
$password = "password";
$dbname = "dbname ";

// Connect to MySQLI and ask it to throw exceptions
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);

try{
	$conn = new mysqli($servername, $username, $password, $dbname);
}catch(mysqli_sql_exception $e){
	print("Database connection error: " . $e->getMessage());
}

// Fetch the payload from Roblox
$payload = json_decode(file_get_contents("php://input"), true);

if (empty($payload)){
	print("Payload from Roblox is empty. No data was received.");
}else{
	$playerID = $payload['PlayerID'];
	
	if (isset($playerID)){
		// Insert a new player ID into the Players table
		$statement = $conn->prepare("
			INSERT INTO `Players`
			(PlayerID, Score1, Score2)
			VALUES
			(?,0,0)
		");
		$statement->bind_param("i", $playerID);
		$statement->execute();

		// Fetch all the players' data and output interface
		$result = $conn->query("SELECT * FROM `Players`");
		while ($row = $result->fetch_assoc()){
			printf("ID %d | Score1: %d Score2 : %d", $row['PlayerID'], $row['Score1'], $row['Score2']);
		}
		print("Finished queries successfully.");
	}else{
		print("No player ID was received.");
	}
}

And see what output return you get from :PostAsync on the Roblox side

2 Likes

Oh thanks , So now it Input data into the Database, but the PlayerID is 0 everytime. Im not sure to understand The " ? " in this part of the code :

	$statement = $conn->prepare("
		INSERT INTO `Players`
		(PlayerID, Score1, Score2)
		VALUES
		(?,0,0)
	");

Here is the output from Roblox :
[PlayerID 0 | Score1: 0 Score2 : 0PlayerID 0 | Score1: 0 Score2 : 0PlayerID 0 | Score1: 0 Score2 : 0Finished queries successfully.]

And here is the database
image

GOT IT !! My PlayerID was a String , So I putted " s " insdead of “i” in the bind_param :smiley:

Big thanks !

One last thing, If I want to get information from the DataBank to Roblox,
On Roblox I probably need to use the HttpService:RequestAsync , But how dont see how it work.
Can you give me an example ?

1 Like

I’m also curious on how this would be done. Bump

I did an other tread and almost figure it out myself

1 Like