How can prepared statements be used in PHP to prevent SQL injection vulnerabilities when interacting with databases?

SQL injection vulnerabilities can be prevented in PHP by using prepared statements. Prepared statements separate SQL code from user input, preventing malicious SQL commands from being injected into the query. This method binds parameters to the query, ensuring that user input is treated as data rather than executable code.

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

// Prepare a SQL query with a placeholder for user input
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

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

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

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