How can SQL Injections be prevented in the PHP code?

SQL Injections can be prevented in PHP code by using prepared statements with parameterized queries. This method allows the database to distinguish between the actual SQL code and the user input, thereby preventing malicious SQL injections.

// Establish a connection to the database
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');

// Prepare a SQL statement with parameters
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username AND password = :password');

// Bind the parameters with user input
$stmt->bindParam(':username', $_POST['username']);
$stmt->bindParam(':password', $_POST['password']);

// Execute the statement
$stmt->execute();

// Fetch the results
$results = $stmt->fetchAll();