A union injection causes additional rows to be added to the result set by using the UNION clause. To do this, we need to know the number of columns in the target result set.

There are two easy strategies for this. Using order by or union. Assume that the following is vulnerable:

SELECT * from users where username='$oops'

order by#

In MySQL you can use numeric arguments for order by which you can use to infer the number of columns. Let $oops = "test' order by 1 -- then the query becomes:

SELECT * from users where username='test' order by 1 -- '

Increase the number until it fails, and you learn the number of columns.

union#

Using the same vulnerable query, you can set $oops = "test' union select 1, 2 -- making the query:

SELECT * from users where username='test' union select 1, 2 -- '

and since the number of columns must match you learn the correct count once the query runs.