What is the purpose of using prepare statements in PHP?

Using prepared statements in PHP helps prevent SQL injection attacks by separating SQL logic from user input. This means that user input is treated as data and not as part of the SQL query, making it safer and more secure. Prepared statements also improve performance by allowing the database to optimize query execution.

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

$stmt = $pdo->prepare('SELECT * FROM users WHERE username = :username');
$stmt->execute(['username' => $username]);

$result = $stmt->fetch();