Home / Learn React / Security: SQL Injection, Validation, Passwords, CSRF

Security: SQL Injection, Validation, Passwords, CSRF

A database app is only as safe as its weakest query. These rules protect your users and your data.

In shortNever join user text into SQL. Use prepared statements, validate on the server, hash passwords, give MySQL a limited user and never expose errors.

Theory in plain words

Two ways to build a queryUnsafe: string join'... WHERE name = '$name'input becomes codeattacker controls SQLSafe: preparedWHERE name = :nameinput stays dataquotes are harmless
Two ways to build a query

What it is

SQL injection happens when user text becomes part of the SQL command. An attacker types SQL instead of a name and the database obeys it.

Why we use it

One unsafe query can leak every user, change prices or delete a table. It is one of the most common ways websites are hacked, and it is easy to prevent.

How it works

A prepared statement sends the SQL and the values separately. The values are always treated as data, never as commands. In PDO: prepare() with placeholders, then execute([...]).

Where it is used

  • Every query that uses a value from the browser: search, login, ids, filters
  • Login forms are the classic target

See the attack (a safe simulation)

This example does not touch a database. It only builds the SQL text so you can see what MySQL would receive. Type x' OR '1'='1 into the box.

Unsafe query text vs prepared statementTry it Yourself

Typing a quote changes the structure of the unsafe query. In the safe version the SQL text never changes.

The fix in PHP

Unsafe vs safe
<?php
// WRONG: never do this
$rows = $pdo->query("SELECT * FROM users WHERE name = '" . $_GET['name'] . "'");

// RIGHT: prepared statement
$st = $pdo->prepare('SELECT id, email FROM users WHERE name = :name');
$st->execute([':name' => $_GET['name'] ?? '']);
$rows = $st->fetchAll();

// Identifiers (column or table names) cannot be placeholders: use a whitelist.
$allowed = ['id', 'title', 'created_at'];
$sort = in_array($_GET['sort'] ?? '', $allowed, true) ? $_GET['sort'] : 'id';
$st = $pdo->query("SELECT id, title FROM notes ORDER BY $sort DESC");

Passwords and login

Other attacks and the defence

AttackWhat happensDefence
SQL injectioninput runs as SQLprepared statements, whitelist for identifiers
XSSinput runs as JavaScript in other visitorsReact escapes text in {}; never use dangerouslySetInnerHTML with user data
CSRFanother site makes your browser send a request with your cookieSameSite cookie, custom header or CSRF token, check method
Broken accessuser changes id in the URL and sees other datacheck user_id in every query on the server
Leaked secretspassword in a public fileconfig outside public_html, never in React or Git
Mass deletebug or abuseleast-privilege DB user, backups

Least privilege MySQL user

Give the app only what it needs
-- In hPanel > Databases create a user, then give only these rights
GRANT SELECT, INSERT, UPDATE, DELETE ON notesapp.* TO 'app_user'@'localhost';
-- Not: DROP, ALTER, CREATE, GRANT, FILE

On Hostinger you pick privileges in hPanel when you attach the user to the database. Use one user per app and a long random password.

Server-side validation

Never trust the browser
$title = trim((string)($b['title'] ?? ''));
if ($title === '' || mb_strlen($title) > 200) json_out(['ok' => false, 'error' => 'Title is required (max 200 characters).'], 422);
$id = filter_var($b['id'] ?? null, FILTER_VALIDATE_INT);
if ($id === false || $id < 1) json_out(['ok' => false, 'error' => 'Bad id'], 422);
Careful:React validation is for comfort. Anyone can skip your React app and call /api/notes.php directly with any data. Only the server check counts.

Quick quiz

1. Which is safe?

2. How do you store passwords?

Common questions

Which is safe?

prepare + execute with placeholders. Prepared statements separate code and data.

How do you store passwords?

password_hash(). password_hash uses a slow, salted algorithm.