Search code examples
phpmysqlisql-injection

How to simulate an SQL Injection attack with mysqli?


I have this code:

if(isset($_POST['submit'])) {
    $name = $_POST['name'];


$query = mysqli_query($conn, "select name from accounts where name = '{$name}'");
if($query) {
   echo "success";
} else {
    echo "error";
}
}
?>



 <form action="" method="post">
                Name: <input type="text" name="name"><br><br>
                <input type="submit" name="submit" value="Add">
</form>

And I have written this in the form and submitted, only return (error), and the table was not deleted. enter image description here


Solution

  • For mysqli, multiple statements or multi queries must be executed with mysqli::multi_query()

    So change

    $query = mysqli_query($conn, "select name from accounts where name = '{$name}'");
    

    to

    $query = mysqli_multi_query($conn, "select name from accounts where name = '{$name}'");
    

    then retry what you want in your own machine.

    Of course, usually hacker will just gain privilege by logging as "admin" and then do whatever he/she wants (in that case just performing single query in a select statement thru a SQL attack will do and do not need to execute multi-queries)

    [additional point]

    For single query SQL attack, submit the following:

    1}' or 1=1 or '{1=1

    which will become:

    select name from accounts where name='{1}' or 1=1 or '{1=1}'
    

    or

    1}' or name='admin' or '{1=1

    which will become:

    select name from accounts where name='{1}' or name='admin' or '{1=1}'
    

    Hence, to avoid SQL attacks, please use parameterized prepared statements. For details, you may refer to :

    php mysqli prepared statements select