How can PHP code be structured to prevent SQL injections in database queries?

To prevent SQL injections in database queries, PHP code can be structured to use prepared statements with parameterized queries. This approach separates SQL logic from user input, ensuring that input values are treated as data and not executable SQL code.

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

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

// Bind input values to parameters
$stmt->bindParam(':username', $_POST['username']);

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

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