What's the best way to connect JavaScript browser games with MySQL databases securely?

I’m pretty new to coding and need some guidance on building a web-based adventure game.

I want to create a simple adventure game that runs in a web browser. My plan is to use MySQL for storing game data, HTML/CSS for the interface, JavaScript for game logic, and PHP to handle database connections.

I found a tutorial that showed me how to send data from JavaScript to PHP like this:

function sendRequest() {
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        // handle response
    };
    xhr.open("GET", "getData.php?playerID=" + playerId, true);
    xhr.send();
}

And the PHP side looks like:

$playerId = $_GET["playerID"];
$query = "SELECT * FROM players WHERE player_id = '" . $playerId . "'";

My main concerns are:

  1. This approach only works with one specific table and query type
  2. I need to access different tables (inventory, quests, stats, etc.)
  3. Security is a big worry - if someone looks at my JavaScript code, they could see how to manipulate my database

Should I create separate PHP files for each type of database operation? How do I prevent people from exploiting my database endpoints? What’s the standard approach for handling multiple database operations securely in browser games?

Been there! Your code has a massive SQL injection vulnerability - attackers could wipe your entire database. Don’t ever concatenate user input directly into SQL queries like that. I built a single PHP endpoint that handles everything through parameters. Use prepared statements and validate everything server-side. Make an api.php that takes an action parameter (getPlayer, updateInventory, whatever) and routes to the right functions. For security - assume everything client-side is compromised. Users can modify JavaScript, intercept requests, and send whatever data they want. Your PHP backend needs to validate permissions, check if players actually own the items they’re trying to use, and verify they can do what they’re asking for. Learned this when players figured out how to give themselves unlimited gold through my terrible endpoints. Server-side validation and proper sessions aren’t optional for multiplayer games.