How can the use of prepared statements improve database interactions in PHP?

Using prepared statements in PHP can improve database interactions by preventing SQL injection attacks and improving performance. Prepared statements separate the SQL query from the user input, which helps to sanitize the input data and prevent malicious code execution. Additionally, prepared statements can be reused with different parameters, reducing the overhead of parsing and optimizing the query each time it is executed.

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

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

// Bind parameters
$stmt->bindParam(':username', $username, 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>";
}