What best practices should be followed when incorporating user input from forms into SQL queries in PHP to avoid security vulnerabilities?

When incorporating user input from forms into SQL queries in PHP, it is essential to use parameterized queries to prevent SQL injection attacks. By binding user input as parameters in the query, you can ensure that the input is treated as data rather than executable SQL code. This practice helps to safeguard your application against security vulnerabilities.

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

// User input from form
$userInput = $_POST['user_input'];

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

// Bind the user input as a parameter
$stmt->bindParam(':username', $userInput);

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

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