How can SQL Injections be prevented when using prepare statements in PHP?

SQL Injections can be prevented when using prepared statements in PHP by properly sanitizing user input and using parameterized queries. Prepared statements separate SQL code from user input, preventing malicious SQL code from being executed.

// 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 placeholder
$stmt->bindParam(':username', $_POST['username']);

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

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