Home › SQL Tutorial › SQL injection and prepared statements
SQL injection and prepared statements
Keep attackers out of your queries.
SQL injection happens when user input is pasted into a query as text. Input like ' OR '1'='1 then changes the meaning of the query. The fix is parameterized (prepared) statements: the query is sent first with a ? placeholder, and the value is sent separately, so it is always treated as data, never as SQL.
Example code
-- UNSAFE: query built by joining strings
-- "SELECT * FROM Customers WHERE name = '" + input + "'"
-- SAFE: prepared statement
PREPARE stmt FROM 'SELECT * FROM Customers WHERE name = ?';
SET @n = ''' OR ''1''=''1';
EXECUTE stmt USING @n;