What is the difference between using a query and a prepared statement in PHP when fetching data from a database?

When fetching data from a database in PHP, using a prepared statement is more secure and efficient compared to using a query. Prepared statements help prevent SQL injection attacks by separating SQL code from user input. They also improve performance by allowing the database to compile and optimize the query once, then execute it multiple times with different parameters.

// Using a prepared statement to fetch data from a database
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();
$result = $stmt->fetch();