What are the potential security risks of directly outputting database query results as links?

Directly outputting database query results as links can expose your application to SQL injection attacks if the links are not properly sanitized. It is important to validate and sanitize the data before outputting it as links to prevent malicious users from injecting harmful code into the URL. One way to mitigate this risk is to use prepared statements with parameterized queries to securely retrieve and display the data.

// Assume $pdo is your PDO database connection object

$stmt = $pdo->prepare("SELECT id, name FROM users WHERE id = :id");
$stmt->bindParam(':id', $id, PDO::PARAM_INT);
$stmt->execute();

while ($row = $stmt->fetch()) {
    $id = htmlspecialchars($row['id']);
    $name = htmlspecialchars($row['name']);
    
    echo "<a href='profile.php?id=$id'>$name</a><br>";
}