Why is it important to use prepared statements or parameterized queries when interacting with a database in PHP?

Using prepared statements or parameterized queries is important when interacting with a database in PHP to prevent SQL injection attacks. These attacks occur when an attacker inserts malicious SQL code into a query, potentially gaining unauthorized access to the database or manipulating its data. Prepared statements or parameterized queries help sanitize user input and ensure that any input provided by the user is treated as data rather than executable code.

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

$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();

// Fetch data from the query
while ($row = $stmt->fetch()) {
    // Do something with the retrieved data
}