What are the benefits of using prepared statements in PHP for database queries?

Using prepared statements in PHP for database queries 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. Additionally, prepared statements make it easier to reuse query templates with different parameters, leading to more maintainable code.

// Example of using prepared statements in PHP for database queries

// Create a database connection
$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
$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>";
}

// Close the connection
$pdo = null;