How can SQL injection vulnerabilities be mitigated in the context of retrieving user IDs from a database in PHP?

SQL injection vulnerabilities can be mitigated by using prepared statements with parameterized queries in PHP. This approach helps to separate SQL code from user input, preventing malicious SQL queries from being executed. By binding parameters to placeholders in the SQL query, the database engine can distinguish between code and data, effectively preventing injection attacks.

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

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

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

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

// Fetch the result
$user_id = $stmt->fetchColumn();

// Use the retrieved user ID as needed
echo "User ID: " . $user_id;