> For the complete documentation index, see [llms.txt](https://riteshs4hu.gitbook.io/infosec-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://riteshs4hu.gitbook.io/infosec-notes/web-appsec/injections/sqli/second-order-injection.md).

# Second Order Injection

Second-Order SQL Injection occurs when malicious input is stored by the application and later used in a SQL query without proper sanitization or parameterization.

Unlike traditional SQL Injection, where the payload is executed immediately, the injected input is first saved in the application's database. The vulnerability is triggered later when the stored data is retrieved and incorporated into another SQL query.

Because the injection does not execute during the initial request, Second-Order SQL Injection is often more difficult to identify during testing.

***

### Vulnerable PHP Code Example

```php
<?php

$conn = mysqli_connect("localhost", "root", "password", "shop");

$username = $_POST['username'];

$query = "INSERT INTO users(username) VALUES('$username')";

mysqli_query($conn, $query);

echo "User registered successfully";

?>
```

Later, another part of the application uses the stored value:

```php
<?php

$conn = mysqli_connect("localhost", "root", "password", "shop");

$username = $row['username'];

$query = "SELECT * FROM orders WHERE username = '$username'";

$result = mysqli_query($conn, $query);

?>
```

***

### Code Explanation

During registration, the application accepts a username from the user:

```php
$username = $_POST['username'];
```

The value is stored directly in the database:

```php
$query = "INSERT INTO users(username) VALUES('$username')";
```

At this point, no obvious issue may occur because the input is only being stored.

Later, the application retrieves the stored username and uses it in another SQL query:

```php
$username = $row['username'];

$query = "SELECT * FROM orders WHERE username = '$username'";
```

Because the stored value is trusted and reused without proper protection, malicious input saved earlier may now affect the SQL query.

***

### How to Exploit

1. Identify functionality that stores user-supplied data in the database.
2. Submit specially crafted input that is accepted and stored by the application.
3. Allow the application to save the data without triggering any immediate errors or unusual behavior.
4. Identify another feature that retrieves and reuses the stored data in a SQL query.
5. When the stored value is later included in a query without proper parameterization, the malicious input influences the SQL statement.
6. The injection executes during this second interaction rather than during the original submission.
7. Depending on the application's functionality and database permissions, the attacker may be able to access, modify, or manipulate data.
