- Before going ahead and exploiting Union-based queries, we need to find the number of columns selected by the server
- Two methods of detecting the number of columns:
- Using `ORDER BY`
- Using `UNION`
## Using `ORDER BY`
- We have to inject a query that sorts the results by a column we specified (e.g., column 1, column 2, and so on) until we get an error saying the column specified does not exist
```mysql
' order by 1-- -
' order by 2-- -
' order by 3-- -
```
## Using `UNION`
- With this method we will get errors until we arrive at the correct column count
```mysql
cn' UNION select 1,2,3-- -
cn' UNION select 1,2,3,4-- -
```
- Results for fist query above
![[images/Pasted image 20251204120809.png]]
- Results for second query above
- Now we know that there are 4 columns![[images/Pasted image 20251204120838.png]]
## Determine Injection Location
- While a query may return multiple columns, the web app may only display some of the columns
- So, if we inject our query in a column that is not printed on the page, we will not get its output
- This is why we need to determine which columns are printed to the page, to determine where to place our injection
- To test that we can get actual data from the database 'rather than just numbers,' we can use the `@@version` SQL query as a test and place it in the second column instead of the number 2
```mysql
cn' UNION select 1,@@version,3,4-- -
```
- As we can see, we can get the database version displayed below
- Now we know how to form our Union SQL injection payloads to successfully get the output of our query printed on the page
![[images/Pasted image 20251204120452.png]]
# Exercise
- Determine column count > 4
- User input: `cn' UNION select 1,2,3,4-- -` ![[images/Pasted image 20251204120809.png]]
- Determine column number for injection location
- User input: `cn' UNION select 1,@@version,3,4-- -` ![[images/Pasted image 20251204120452.png]]
- Replace `@@version` with `user()` to determine current user
- User input: `cn' UNION select 1, user(),3,4-- -`