How can prepared statements be used to prevent SQL injection in PHP when querying a database?

SQL injection can be prevented in PHP by using prepared statements. Prepared statements separate the SQL query from the user input, which prevents malicious SQL code from being executed. This is done by sending the SQL query and parameters separately to the database, 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 statement with placeholders
$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');

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

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

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