How can I prevent SQL injection in PHP 8.2? EXAMPLES

How to quickly and effectively prevent SQL injections. Here are some examples which should be followed throughout the project

First of all, before I go into select, update or insert commands, it is important to establish the connection to the data correctly from the beginning. This is the first important step to more security.

$dbConnection = new PDO('mysql:dbname=dbtest;host=127.0.0.1;charset=utf8mb4', 'username', 'password');

$dbConnection->setAttribute(PDO::ATTR_EMULATE_PREPARES, false);
$dbConnection->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);

Prevent SQL injection

To prevent SQL injection in PHP using PDO (PHP Data Objects), follow these guidelines:

  1. Use Prepared Statements: Prepared statements are the most effective way to prevent SQL injection. PDO supports prepared statements, which separate SQL code from user-supplied data.

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
  1. Parameterize Queries: Instead of directly concatenating user input into the query string, use placeholders (named or positional) and bind the user input as parameters to the prepared statement.

$stmt = $pdo->prepare("INSERT INTO users (username, password) VALUES (:username, :password)");
$stmt->bindParam(':username', $username);
$stmt->bindParam(':password', $password);
$stmt->execute();
  1. Avoid Dynamic Query Building: Minimize the use of dynamic SQL queries where user input is directly concatenated into the query string. Instead, use prepared statements and dynamic query building techniques.

$sql = "SELECT * FROM users WHERE 1=1";
$params = array();

if (!empty($username)) {
    $sql .= " AND username = :username";
    $params[':username'] = $username;
}

if (!empty($email)) {
    $sql .= " AND email = :email";
    $params[':email'] = $email;
}

$stmt = $pdo->prepare($sql);
$stmt->execute($params);
  1. Input Validation and Sanitization: Validate and sanitize user input before using it in queries. Although prepared statements provide significant protection, validating and sanitizing input adds an extra layer of security.

$username = $_POST['username'];

if (preg_match('/^[a-zA-Z0-9]+$/', $username)) {
    // Valid username
} else {
    // Invalid username
}