What best practices should be followed when creating dynamic links in PHP that include data from a database?

When creating dynamic links in PHP that include data from a database, it is important to properly sanitize the input data to prevent SQL injection attacks. One way to do this is by using prepared statements with parameterized queries to securely pass the data from the database to the dynamic link.

<?php
// Assume $db is the database connection object

// Get data from the database
$stmt = $db->prepare("SELECT id, name FROM users WHERE id = ?");
$stmt->bind_param("i", $userId);
$userId = 1; // Example user ID
$stmt->execute();
$result = $stmt->get_result();
$user = $result->fetch_assoc();

// Create dynamic link with data from the database
$link = "<a href='profile.php?id=" . htmlspecialchars($user['id']) . "'>" . htmlspecialchars($user['name']) . "</a>";

echo $link;
?>