How can prepared statements be utilized in PHP to prevent SQL Injection in database queries?

SQL Injection can be prevented in PHP by using prepared statements. Prepared statements separate SQL code from user input, preventing malicious input from altering the SQL query structure. This helps to protect the database from unauthorized access or data manipulation.

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

// Prepare a SQL query using a prepared statement
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");

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

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

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