What are the recommended methods for handling data retrieval and output in PHP scripts?
When handling data retrieval and output in PHP scripts, it is recommended to use prepared statements to prevent SQL injection attacks and sanitize user input to avoid cross-site scripting vulnerabilities. Additionally, using proper error handling techniques can help in debugging and troubleshooting data retrieval issues.
// Example of using prepared statements for data retrieval
$pdo = new PDO("mysql:host=localhost;dbname=mydatabase", "username", "password");
$stmt = $pdo->prepare("SELECT * FROM users WHERE id = :id");
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
$stmt->execute();
$user = $stmt->fetch();
// Example of sanitizing user input for output
$username = htmlspecialchars($user['username']);
// Example of error handling
if(!$user) {
echo "User not found.";
} else {
echo "Username: " . $username;
}