In the context of PHP development, what are the advantages of using prepared statements over direct SQL queries, and how can they be implemented effectively to enhance code quality and security?

Using prepared statements in PHP development offers several advantages over direct SQL queries, such as preventing SQL injection attacks, improving code readability, and enhancing performance by reusing query plans. To implement prepared statements effectively, you can use PDO (PHP Data Objects) or MySQLi extension in PHP to prepare, bind parameters, execute, and fetch results from the database.

// Using PDO to implement prepared statements in PHP
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');

// Prepare a SQL statement
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');

// Bind parameters
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);

// Execute the statement
$stmt->execute();

// Fetch results
$user = $stmt->fetch(PDO::FETCH_ASSOC);