How can PHP developers prevent SQL injections in their code?

SQL injections can be prevented in PHP code by using prepared statements with parameterized queries. This approach separates SQL code from user input, preventing malicious SQL queries from being executed. By using placeholders for user input values, the database engine can distinguish between code and data, effectively neutralizing the risk of SQL injection attacks.

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

// Prepare a SQL statement with a placeholder for user input
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

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

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

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