What are the benefits of using prepared statements in PHP when interacting with a database?

Using prepared statements in PHP when interacting with a database helps prevent SQL injection attacks by separating SQL logic from user input. Prepared statements also improve performance by allowing the database to optimize query execution plans. Additionally, prepared statements make code more readable and maintainable by clearly separating SQL commands from data values.

// Using prepared statements in PHP to interact with a database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

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

// Bind parameters
$stmt->bindParam(':email', $email, PDO::PARAM_STR);

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

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

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