How can prepared statements be used effectively to prevent SQL injections in PHP?

To prevent SQL injections in PHP, prepared statements can be used effectively. Prepared statements separate SQL code from user input, which helps to prevent malicious SQL injections by treating input as data rather than executable code. This approach allows the database to distinguish between SQL code and data, making it more secure.

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

// Prepare a SQL statement 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', $username);

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

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