What is the purpose of using prepared statements in PHP?

Using prepared statements in PHP helps prevent SQL injection attacks by separating SQL logic from data input. Prepared statements allow for the reuse of SQL queries with different parameters, improving performance. Additionally, prepared statements automatically handle escaping special characters in input data, reducing the risk of errors in SQL queries.

// Example of using prepared statements in PHP
$pdo = new PDO('mysql:host=localhost;dbname=my_database', 'username', 'password');

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

while ($row = $stmt->fetch()) {
    echo $row['username'] . '<br>';
}