How can SQL injection be prevented in PHP when constructing SQL queries?

SQL injection can be prevented in PHP by using prepared statements with parameterized queries. This approach separates the SQL query logic from the user input, preventing malicious SQL code from being injected into the query.

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

// Prepare a SQL statement with a parameterized query
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

// Bind the parameter value to the query
$stmt->bindParam(':username', $_POST['username']);

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

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