What are the best practices for handling and displaying data retrieved from a database in PHP?
When handling and displaying data retrieved from a database in PHP, it is important to sanitize the data to prevent SQL injection attacks and ensure proper formatting for display. One way to do this is by using prepared statements to safely retrieve data from the database and then properly escape and format it before displaying it on the webpage.
// Connect to the database
$pdo = new PDO('mysql:host=localhost;dbname=mydatabase', 'username', 'password');
// Prepare a statement to retrieve data
$stmt = $pdo->prepare('SELECT * FROM users WHERE id = :id');
$stmt->bindParam(':id', $userId, PDO::PARAM_INT);
$stmt->execute();
// Fetch the data and display it
while ($row = $stmt->fetch()) {
$username = htmlspecialchars($row['username']);
$email = filter_var($row['email'], FILTER_SANITIZE_EMAIL);
echo "Username: $username <br>";
echo "Email: $email <br>";
}