35. Using a database safely
How SQL injection happens and how parameters stop it, giving only the rights a job needs, backups, and the habits that keep data from being lost.
SQL injection: when a user's text becomes a statement
Our shop has a product search box on its website. The user types a product name, and the program joins that text into an SQL statement, like this (in no language in particular):
sql = "SELECT name, price FROM product WHERE name = '" + text + "'"
If the user types Coffee, the statement is:
SELECT name, price FROM product WHERE name = 'Coffee';| name | price |
|---|---|
| Coffee | 55.0 |
One row, Coffee: all good. But suppose someone with bad intentions types this into the search box:
x' OR '1'='1
The ' they typed closes our text too early, and the rest becomes SQL, no longer a product name:
SELECT name, price FROM product WHERE name = 'x' OR '1'='1';| name | price |
|---|---|
| Coffee | 55.0 |
| Green Tea | 45.0 |
| Orange Juice | 40.0 |
| Croissant | 35.0 |
| Banana Bread | 60.0 |
| Cheesecake | 120.0 |
| Potato Chips | 25.0 |
| Dried Mango | 90.0 |
| Cashew Nuts | 150.0 |
| Notebook | 30.0 |
| Pen | 15.0 |
| Highlighter | 25.0 |
'1'='1' is always true, so the query gives all 12 products. No harm done to the shop yet, but look at another text:
x' UNION SELECT name, phone FROM customer --
SELECT name, price FROM product WHERE name = 'x' UNION SELECT name, phone FROM customer --';| name | price |
|---|---|
| Anan Wongsa | NULL |
| Kanya Boonmee | 084-246-1357 |
| Lalita Meesuk | 087-654-3210 |
| Malee Srisuk | 089-111-2222 |
| Narin Thongdee | 082-777-8888 |
| Pim Chaiya | 086-555-0101 |
| Siriporn Kaewdee | NULL |
| Somchai Jaidee | 081-234-5678 |
| Tawan Rungruang | 085-123-4567 |
| Wichai Saelim | 083-999-0000 |
The product search has become a way to read the names and phone numbers of all 10 customers (the phones show up in a column called price). The -- turns our last ' into a comment, so the statement is still valid SQL. This is SQL injection, a hole through which countless databases have leaked.
At a login page it is worse. If the program joins text the same way and someone types the name admin' --, the statement becomes this (the practice shop has no users table, so it is only shown):
SELECT id FROM users WHERE name = 'admin' --' AND password = 'anything';The whole password check is now a comment: they are in as admin without knowing the password. And if the program runs several statements in one call (Phai SQL's execute runs every statement separated by ;), a text like x'; DELETE FROM orders; -- deletes every order.
"Filtering out the '" or replacing it yourself is not a good fix: forget it in one place and you leak, and there are other ways around it. The right way is never to join a user's text into an SQL statement at all. Use parameters, as the next section shows.
Parameters: the statement and the values kept apart
Instead of joining text, you write the statement with a place left for each value and send the values separately. Those places are parameters, and they can be written several ways:
| Form | Example | The value comes from |
|---|---|---|
? | WHERE name = ? | the values in order: the first, the second, ... |
?1, ?2 | WHERE id = ?2 | the second value (can be used again in the statement) |
:name | WHERE name = :name | the value with that name (can be used again too) |
SELECT name, price FROM product WHERE name = ?;
UPDATE product SET stock = stock - ?1 WHERE id = ?2;
SELECT id, name FROM customer WHERE city = :city AND joined >= :since;Why it is safe: the database reads and understands the statement before it sees any value. By then it knows the statement is only "find the products whose name equals a value", so whatever comes later can only be a value, never part of the statement, however many ' or -- it holds. The text x' OR '1'='1 sent as a parameter is a search for a product named x' OR '1'='1, letter for letter, the same as this statement (in SQL, a ' inside text is written ''):
SELECT name, price FROM product WHERE name = 'x'' OR ''1''=''1';| name | price |
|---|
There is no product of that name, so 0 rows: exactly right.
In a Rust program with Phai SQL, the parameters' values are a list of Values, in order (?, ?N and :name all work; names are numbered in the order they first appear in the statement):
use phai_sql::{Database, Value};
// Product search: text is whatever the user typed, and stays a value
let db = Database::open("shop.db")?;
let r = db.query(
"SELECT name, price FROM product WHERE name = ?",
&[Value::Text(text.to_string())],
)?;
// Find by id
let r = db.query("SELECT name, price FROM product WHERE id = ?", &[Value::Integer(5)])?;
// Take from stock: ?1 is how many, ?2 the product
let db = Database::open_writable("shop.db")?;
db.execute(
"UPDATE product SET stock = stock - ?1 WHERE id = ?2",
&[Value::Integer(2), Value::Integer(5)],
)?;
Every language has the same thing, sometimes under another name (prepared statements, bound parameters). The idea is always a fixed statement, with the values sent apart:
Python: cur.execute("SELECT name FROM product WHERE name = ?", (text,))
PHP PDO: $st = $pdo->prepare("SELECT name FROM product WHERE name = :name");
$st->execute(['name' => $text]);
A parameter can stand only for a value, not for a table's or a column's name. If users may choose the column to sort by, check their choice against a list of names the program knows (name, price) and use the name from that list, never their text. A "contains" search still works with a parameter: WHERE name LIKE ?, with the value '%' + text + '%'.
Only the rights a job needs
However well a program is written, it may slip somewhere. Least privilege means each program and each person can do only what their work needs, so that a slip can do only that much harm.
- A program that only reads opens the file read only. In Phai SQL,
Database::openopens a file for reading: no statement that changes data can run. KeepDatabase::open_writablefor programs that must write. A sales report page needs only the first. - The server's users. When Phai SQL runs as a server (for programs that speak to MySQL), each user has one of three roles:
ownercan do everything;ai(for AI agents) andguestcan only read, and the columns the owner marks as private (in the table_phai_columns) come back masked and can't be used inWHERE,ORDER BYor a join, so their real values can't be guessed one try at a time. Give an AI or an outsider one of these roles, neverowner. - Never keep passwords as plain text in a table. Keep a hash made with a method meant for passwords: if the file leaks, the passwords still don't.
Backups
Data can be lost in many ways: a disk fails, a file is deleted, or we run a wrong DELETE ourselves. One thing helps in every case: a backup, made regularly.
VACUUM INTO writes a copy of the whole database into a new file, packed and complete, while the database stays in use (this example writes a file, so it is shown, not run):
VACUUM INTO 'backup-2026-12-02.db';The file must not exist yet (if it does, it is an error), which is why a date in its name is the custom.
- Don't copy a database file while another program is writing to it: the copy may be caught halfway. Use
VACUUM INTO, or copy when nobody is using it. - Keep backups somewhere else. A backup on the same disk goes when the disk goes.
- Open a backup now and then. A backup never tried may not work on the day it is needed.
Once a backup is open, have the database check the whole file with PRAGMA integrity_check. A good file answers with one word, ok; a damaged one says where it is damaged:
PRAGMA integrity_check;| integrity_check |
|---|
| ok |
Habits before changing data
UPDATE and DELETE have no undo button, and forget the WHERE and they change every row of the table. These habits catch nearly every slip:
- Try it on a copy first. For a big change, make a copy with
VACUUM INTOand try the change there until you are sure. SELECTwith the sameWHEREfirst. See that it gives exactly the rows you mean to change, no more and no fewer. Then turn theSELECT ...intoUPDATE ... SET ..., keeping theWHEREletter for letter.BEGINbefore a risky change. Make the change and look at the result: if it is right,COMMIT; if not,ROLLBACKand everything is as it was (chapter 19).
For example, to raise the price of the stationery (category 4) by 5 baht each, first see which rows it will touch:
SELECT id, name, price FROM product WHERE category_id = 4;| id | name | price |
|---|---|---|
| 10 | Notebook | 30.0 |
| 11 | Pen | 15.0 |
| 12 | Highlighter | 25.0 |
3 rows, as meant. Now make the change inside a transaction and look before deciding:
BEGIN;
UPDATE product SET price = price + 5 WHERE category_id = 4;
SELECT id, name, price FROM product WHERE category_id = 4;| id | name | price |
|---|---|---|
| 10 | Notebook | 35.0 |
| 11 | Pen | 20.0 |
| 12 | Highlighter | 30.0 |
Say you change your mind (or see a mistake): ROLLBACK, and all 3 prices are back as they were:
ROLLBACK;
SELECT id, name, price FROM product WHERE category_id = 4;| id | name | price |
|---|---|---|
| 10 | Notebook | 30.0 |
| 11 | Pen | 15.0 |
| 12 | Highlighter | 25.0 |
RETURNING (chapter 18) helps too: UPDATE ... RETURNING id, price tells you at once which rows changed and to what.
NULL traps
NULL means "unknown" (chapter 5), and it is behind most queries that "look right but give the wrong answer". The traps people fall into most:
SELECT count(*), count(phone) FROM customer;| count(*) | count(phone) |
|---|---|
| 10 | 8 |
count(*) counts every row (10), but count(phone) skips the rows whose phone is NULL (8).
SELECT count(*) FROM customer WHERE phone <> '081-234-5678';| count(*) |
|---|
| 7 |
7, not 9: for the 2 customers with no phone, NULL <> '...' isn't "true" but NULL, so their rows drop out. Were this a DELETE, it would quietly leave them behind.
SELECT NULL = NULL, NULL IS NULL, 'a' || NULL, coalesce(phone, '-') FROM customer WHERE id = 3;| NULL = NULL | NULL IS NULL | 'a' || NULL | coalesce(phone, '-') |
|---|---|---|---|
| NULL | 1 | NULL | - |
= NULLis never true: useIS NULLorIS NOT NULL.- Anything joined to
NULLisNULL: give it a stand-in withcoalesce()first. NOT INa list that holds aNULLgives no rows at all:
SELECT name FROM product WHERE id NOT IN (SELECT 1 UNION SELECT NULL);| name |
|---|
0 rows, although 11 products aren't id 1. When the list comes from a subquery that might hold a NULL, use NOT EXISTS instead, or filter the NULLs out in the subquery.
- A program joins text like this:
"SELECT id, name FROM customer WHERE city = '" + text + "'". If someone typesx' OR '1'='1, what does the statement become? Run it and see how many rows it gives. - Write the statement of exercise 1 again with the parameter
:city(just write it, don't run it), then run the statement that is the same as sending that text as a value. - You want to cut the price of the sold-out products (
stock = 0) by 10%.SELECTfirst to see how many it touches, then change them in a transaction withRETURNINGto see the new prices, andROLLBACK.
Show the answer
SELECT id, name FROM customer WHERE city = 'x' OR '1'='1';
-- Exercise 2: SELECT id, name FROM customer WHERE city = :city
SELECT id, name FROM customer WHERE city = 'x'' OR ''1''=''1';
SELECT id, name, price FROM product WHERE stock = 0;
BEGIN;
UPDATE product SET price = price * 0.9 WHERE stock = 0 RETURNING id, name, price;
ROLLBACK;| id | name |
|---|---|
| 1 | Somchai Jaidee |
| 2 | Malee Srisuk |
| 3 | Anan Wongsa |
| 4 | Pim Chaiya |
| 5 | Narin Thongdee |
| 6 | Kanya Boonmee |
| 7 | Wichai Saelim |
| 8 | Siriporn Kaewdee |
| 9 | Tawan Rungruang |
| 10 | Lalita Meesuk |
| id | name |
|---|
| id | name | price |
|---|---|---|
| 3 | Orange Juice | 40.0 |
| 12 | Highlighter | 25.0 |
| id | name | price |
|---|---|---|
| 3 | Orange Juice | 36.0 |
| 12 | Highlighter | 22.5 |
Phai (bamboo), given as a gift of knowledge: free to use, learn from and pass on · every example on this page was run on Phai SQL and checked against SQLite when the page was made