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';
nameprice
Coffee55.0
1 row

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';
nameprice
Coffee55.0
Green Tea45.0
Orange Juice40.0
Croissant35.0
Banana Bread60.0
Cheesecake120.0
Potato Chips25.0
Dried Mango90.0
Cashew Nuts150.0
Notebook30.0
Pen15.0
Highlighter25.0
12 rows

'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 --';
nameprice
Anan WongsaNULL
Kanya Boonmee084-246-1357
Lalita Meesuk087-654-3210
Malee Srisuk089-111-2222
Narin Thongdee082-777-8888
Pim Chaiya086-555-0101
Siriporn KaewdeeNULL
Somchai Jaidee081-234-5678
Tawan Rungruang085-123-4567
Wichai Saelim083-999-0000
10 rows

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:

FormExampleThe value comes from
?WHERE name = ?the values in order: the first, the second, ...
?1, ?2WHERE id = ?2the second value (can be used again in the statement)
:nameWHERE name = :namethe 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';
nameprice
no rows

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.

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.

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
1 row

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:

  1. Try it on a copy first. For a big change, make a copy with VACUUM INTO and try the change there until you are sure.
  2. SELECT with the same WHERE first. See that it gives exactly the rows you mean to change, no more and no fewer. Then turn the SELECT ... into UPDATE ... SET ..., keeping the WHERE letter for letter.
  3. BEGIN before a risky change. Make the change and look at the result: if it is right, COMMIT; if not, ROLLBACK and 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;
idnameprice
10Notebook30.0
11Pen15.0
12Highlighter25.0
3 rows

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;
idnameprice
10Notebook35.0
11Pen20.0
12Highlighter30.0
3 rows

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;
idnameprice
10Notebook30.0
11Pen15.0
12Highlighter25.0
3 rows

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)
108
1 row

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
1 row

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 = NULLNULL IS NULL'a' || NULLcoalesce(phone, '-')
NULL1NULL-
1 row
SELECT name FROM product WHERE id NOT IN (SELECT 1 UNION SELECT NULL);
name
no rows

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.

  1. A program joins text like this: "SELECT id, name FROM customer WHERE city = '" + text + "'". If someone types x' OR '1'='1, what does the statement become? Run it and see how many rows it gives.
  2. 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.
  3. You want to cut the price of the sold-out products (stock = 0) by 10%. SELECT first to see how many it touches, then change them in a transaction with RETURNING to see the new prices, and ROLLBACK.
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;
idname
1Somchai Jaidee
2Malee Srisuk
3Anan Wongsa
4Pim Chaiya
5Narin Thongdee
6Kanya Boonmee
7Wichai Saelim
8Siriporn Kaewdee
9Tawan Rungruang
10Lalita Meesuk
10 rows
idname
no rows
idnameprice
3Orange Juice40.0
12Highlighter25.0
2 rows
idnameprice
3Orange Juice36.0
12Highlighter22.5
2 rows

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