How can developers ensure the security of their PHP code when handling user input and database queries?

Developers can ensure the security of their PHP code when handling user input and database queries by using prepared statements to prevent SQL injection attacks and validating user input to prevent cross-site scripting attacks. Additionally, developers should always sanitize and escape user input before using it in database queries to prevent malicious code execution.

// Using prepared statements to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();

// Validating user input to prevent cross-site scripting
$username = htmlspecialchars($_POST['username'], ENT_QUOTES, 'UTF-8');

// Sanitizing and escaping user input before using it in database queries
$username = mysqli_real_escape_string($conn, $_POST['username']);