What are the recommended methods for handling and displaying SQL query results in PHP to prevent data leakage or manipulation?

To prevent data leakage or manipulation when handling and displaying SQL query results in PHP, it is recommended to use prepared statements with parameterized queries to prevent SQL injection attacks. Additionally, always sanitize and validate user input to prevent cross-site scripting (XSS) attacks. Finally, limit the amount of data returned in query results to only what is necessary to reduce the risk of exposing sensitive information.

// Example of using prepared statements with parameterized queries to prevent SQL injection
$stmt = $pdo->prepare("SELECT * FROM users WHERE username = :username");
$stmt->bindParam(':username', $username);
$stmt->execute();
$results = $stmt->fetchAll();

// Example of sanitizing and validating user input to prevent XSS attacks
$username = htmlspecialchars($_POST['username']);

// Example of limiting query results to reduce risk of data exposure
$stmt = $pdo->prepare("SELECT id, username FROM users WHERE id = :id");
$stmt->bindParam(':id', $id);
$stmt->execute();
$results = $stmt->fetchAll();