How to use SQL database in roblox

If you’re using a off site database and free hosting site, 9 times out of 10 it’s because you have a invalid SSL certificate. Usually your hosting service will provide you with one if you ask. The reason it doesn’t ever parse is because you’re using a http protocol for it, even using a https without a valid certificate won’t work either. I had just figured it out after i tried fixing it for 2 hours. Since I use a php/SQL database, and I have a script that displays the json document, I had to get a valid SSL certificate. This was for a ban system. If anyone needs further information I’ll gladly help out.

Firstly, if you want to use this hosting service, you completely can, you will have to create an account and setup your website by following this link
I am using the 000webhost method.
https://www.000webhost.com/free-website-sign-up --EXTERNAL OFF PLATFORM LINK
to create a new account on 000webhost
Second, you need to create a website, make sure you fill out all fields.


After you do that make sure you select “UPLOAD SITE

Then select public_html

Then create a new file

and name it index.php
After that, you need to go back to the home page, click manage, and scroll down to databases


Make sure you save all of these for later

image
Navigate to the SQL tab and paste the script given below

CREATE TABLE players (
  id INT AUTO_INCREMENT PRIMARY KEY,
  UserId BIGINT NOT NULL
);

INSERT INTO players (UserId) VALUES (123),(1234),(12345);

Then go back to your file manager and navigate to index.php, then insert this script, save it, and open up roblox studio

<?php
// Database connection variables
$servername = "name of server, localhost if not on a website";
$username = "databaseusername";
$password = "databasepassword";
$dbname = "databasename";

// Create database connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// SQL query to retrieve data
$sql = "SELECT `UserId` FROM `players` WHERE 1"; 
$result = $conn->query($sql);

// Check for errors
if (!$result) {
    die("Query failed: " . $conn->error);
}

// Output data as a JSON page
header('Content-Type: application/json');
if ($result->num_rows > 0) {
    $data = array();
    while($row = $result->fetch_assoc()) {
        $data[] = array("UserId" => (int)$row["UserId"]);
    }
    echo json_encode($data);
} else {
    echo json_encode("0 results");
}
?>

You just insert this code into your websites htdocs as a new php script and it should display as the webpage.
(you will need to name it the URL path you want to have in place, this doesn’t speak for everybody, but since I’m using a hosting site with a filemanager, I need that.

The select ‘userid’ part of my php script gets the argument that the sql databse has in place, in my case, mine looks like this:

if you use a regular myphp sql database then it will have that query. Personally, to get all my rows in without writing them in manually is this:

CREATE TABLE players ( --this creates a new table called "players" in your database.
  id INT AUTO_INCREMENT PRIMARY KEY,
  UserId BIGINT NOT NULL --userid being the column of the table
);

INSERT INTO players (UserId) VALUES (Your data),(Your data),(Your data); -- this adds these results or fields into the userid column

Alternateively, if you don’t have a predetermined sql database key, then you can add this to the top of the script:

USE nameofdatabase; --you put the name of your database in here
CREATE USER 'newuser'@'localhost' IDENTIFIED BY 'password';
GRANT ALL PRIVILEGES ON nameofdatabase.* TO 'newuser'@'localhost';
FLUSH PRIVILEGES;

From there, you input the new fields into the php script that will call the database.

Next, you will need a roblox script that will call the data, this is how you do it:

local HttpService = game:GetService('HttpService')
local url = 'https://yoururl' 


local httpService = game:GetService("HttpService")
local response = httpService:GetAsync(url)

-- Convert the response from JSON to a Lua table
local players = httpService:JSONDecode(response)

for _, player in pairs(game.Players:GetPlayers()) do
	for _, data in pairs(players) do
		if player.UserId == data.UserId then --data.userid being the name of the field, or as in the text after the field, the name and stuff is easily able to be edited in the script to make the data parsable. [{"UserId":thedataintheuseridfield}]  for example.
			player:Kick("You have been banned.")
			break
		end
	end
end

in my case, i call my .json file as a banlist. if you know a bit about scripting then you will know how you can edit this.

Next is how to write to your .json

local HttpService = game:GetService('HttpService')
local url = 'https://yoururl'

-- Make a HTTP GET request to the endpoint URL
local httpService = game:GetService("HttpService")
local response = httpService:GetAsync(url)
local newPlayer = { what_your_column_name_is = data} --this is the data you're sending to the json

-- Convert player data to JSON string
local requestBody = HttpService:JSONEncode(newPlayer)

-- Set up request options
local request = {
	Url = url,
	Method = "POST",
	Headers = {
		["Content-Type"] = "application/json"
	},
	Body = requestBody
}

-- Send POST request
local response2 = HttpService:RequestAsync(request)
--Error handling
if response2.Success then
	print("Player added to data table!")
else
	warn("Failed to add player to data table:", response2.StatusCode, response2.StatusMessage)
end

now to get the post request, your php script should look like this:

<?php
// Database connection variables
$servername = "servername";
$username = "username";
$password = "password";
$dbname = "databasename";

// Create database connection
$conn = new mysqli($servername, $username, $password, $dbname);

// Check connection
if ($conn->connect_error) {
    die("Connection failed: " . $conn->connect_error);
}

// Process incoming POST request to add new player data
if ($_SERVER['REQUEST_METHOD'] == 'POST') {
    // Retrieve and decode the JSON payload from the request body
    $postData = json_decode(file_get_contents('php://input'), true);
    
    // Check for errors in decoding JSON
    if (json_last_error() !== JSON_ERROR_NONE) {
        http_response_code(400); // Bad Request
        echo json_encode("Invalid request data");
        exit;
    }
    
    // Extract player data from decoded payload
    $newUserId = $postData["UserId"];
    
    // SQL query to add new player data
    $sql = "INSERT INTO players (UserId) VALUES ('$newUserId')";
    
    // Execute SQL query
    if ($conn->query($sql) === TRUE) {
        http_response_code(201); // Created
        echo json_encode("New player data added successfully");
    } else {
        http_response_code(500); // Internal Server Error
        echo json_encode("Error adding new player data: " . $conn->error);
    }
    exit;
}

// SQL query to retrieve data
$sql = "SELECT `UserId` FROM `players` WHERE 1";
$result = $conn->query($sql);

// Check for errors
if (!$result) {
    die("Query failed: " . $conn->error);
}

// Output data as a JSON page
header('Content-Type: application/json');
if ($result->num_rows > 0) {
    $data = array();
    while($row = $result->fetch_assoc()) {
        $data[] = array("UserId" => (int)$row["UserId"]);
    }
    echo json_encode($data);
} else {
    echo json_encode("0 results");
}
?>

Thank you all for reading.

You should add API Credentials to your server to prevent unauthorized MySQL queries.

Yes, you should do that if you have a post request process. But for me since I don’t have post reqests enabled, I have no need to use that as my sql database isnt traceable.