What best practices should be followed when structuring PHP code to handle user input and database queries to prevent SQL injection attacks?

To prevent SQL injection attacks, it is crucial to use parameterized queries when interacting with a database in PHP. This involves using prepared statements with placeholders for user input, which are then bound to the actual values before execution. By doing this, the database engine can distinguish between SQL code and user input, effectively preventing malicious SQL injection attacks.

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

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

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

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

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