When using PHP to interact with a MySQL database, what steps should be taken to prevent SQL injection vulnerabilities when incorporating user input into queries?

To prevent SQL injection vulnerabilities when incorporating user input into queries in PHP, it is crucial to use prepared statements with parameterized queries. This helps to separate the SQL query logic from the user input, preventing malicious SQL code from being executed. By binding parameters to placeholders in the query, the database system can distinguish between code and data, effectively protecting against SQL injection attacks.

// Establish a connection to the MySQL database
$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 user input to the parameter
$stmt->bindParam(':username', $_POST['username']);

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

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