How can PDO Prepared Statements be utilized effectively in PHP to prevent SQL injection and improve performance?

To prevent SQL injection and improve performance in PHP, PDO Prepared Statements can be utilized effectively. Prepared Statements separate SQL logic from data input, preventing malicious SQL injection attacks. Additionally, Prepared Statements can be reused with different parameters, improving performance by reducing the need for repetitive query parsing.

// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

// Bind parameters and execute the statement
$username = $_POST['username'];
$stmt->bindParam(':username', $username);
$stmt->execute();

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

// Loop through the results
foreach ($results as $row) {
    echo $row['username'] . '<br>';
}