How can I carry out SQL insert injection when there’s a select statement beforehand


So here’s the deal. I’ve been working on an SQL injection challenge and here’s what comes up.

There’s a registration page where you input your Username, password and confirm password. It’s vulnerable to INSERT SQL injection, I’m basically trying to insert my own data and make myself and admin (admin=1). However, there is a SELECT statement before the INSERT statement that checks if the username exists in the database. The problem is, if I try inserting data with SQL injection, the SELECT statement will fail and will generate an error, and the INSERT statement will never be executed.

I’ve made an in-a-nutshell PHP code to show you how it works.

<?php     $  username = $  _POST['username'];     $  password = md5($  _POST['password']);      $  sql = mysqli_query("SELECT * FROM users WHERE username = '$  username';");     if(mysqli_num_rows($  sql) > 0 || !$  sql) {         // this code will be run if the username already exists OR an SQL error in the query above.     }     else {         $  sql = mysqli_query("INSERT INTO users (`id`,`username`,`password`,`admin`) VALUES (NULL,'$  username','$  password',0);");     } ?> 

So the thing is, if I tried signing up with the username "admintest','password',1);-- " which should in theory INSERT myself into the database as an admin, here comes the problems.

The problem, is the SELECT query. Watch what happens.

SELECT * FROM users WHERE username = 'admintest','password',1);-- '; 

This of course is a syntax-error, and as we saw by the code I provided above, an IF statement will confirm that the SQL query was a syntax error, and the INSERT statement will NEVER run.

In an ideal world, this should happen in the INSERT statement, which will insert me as an ADMIN.

INSERT INTO users (`id`,`username`,`password`,`admin`) VALUES (NULL,'admintest','password',1);-- ','password',0); 

I’ve tried to work out something that doesn’t generate a syntax error on the SELECT, and also INSERTs the data I want to insert. Would be appreciated if anyone could help out 🙂