> For the complete documentation index, see [llms.txt](https://dev-angelist.gitbook.io/ewptxv3-notes/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://dev-angelist.gitbook.io/ewptxv3-notes/readme/5.5-other-common-web-attacks-1/system-security-1/4.3.7-mitigation-strategies.md).

# 4.3.7 Mitigation Strategies

{% embed url="<https://cheatsheetseries.owasp.org/cheatsheets/SQL_Injection_Prevention_Cheat_Sheet.html>" %}

## Mitigation Strategies

Mitigating SQL injection vulnerabilities is crucial for securing web applications. Here are some effective strategies that can be proposed to clients to address and prevent SQL injection attacks:

### **Prepared Statements**

**Description:**

* **What it is:**
  * Prepared statements separate SQL code from user inputs by using bind variables.
  * This is considered the best solution to mitigate SQL injection.
* **Implementation Example (PHP):**

  ```php
  $sql = "INSERT INTO test_table VALUES (?, ?, ?, ?)";
  $sql_statement = $mysqli->prepare($sql);
  $sql_statement->bind_param('dsss', $user_id, $name, $address, $email);
  $user_id = $_POST['user_id'];
  $name = $_POST['name'];
  $address = $_POST['address'];
  $email =  $_POST['email'];
  $sql_statement->execute();
  ```

**Recommendation:**

* Implementing prepared statements might require code refactoring but provides a robust long-term solution.

### **Type Casting**

**Description:**

* **What it is:**
  * Type casting involves explicitly converting user inputs to a specific data type, particularly useful for integer numbers.
* **Implementation Example (PHP):**

  ```php
  $user_id = (int) $user_id;
  ```

**Recommendation:**

* Type casting offers a short-term method to prevent SQL injection, especially for numeric values.

### **Input Validation**

**Description:**

* **What it is:**
  * Input validation checks user inputs against a predefined set of rules, allowing only valid inputs.
* **Implementation Example (PHP):**

  ```php
  if (!preg_match('|^[a-z\s-]$|i', $name)) {
      die('Please enter a valid name');
  }
  ```

**Recommendation:**

* Input validation acts as a good practice to supplement other security measures.
* White-list-based validation, allowing only specific characters, can enhance security.
