What is the best practice for handling URLs in PHP when generating dynamic content from a database query?

When generating dynamic content from a database query in PHP, it is best practice to properly encode and sanitize any URLs to prevent security vulnerabilities such as SQL injection or XSS attacks. One way to achieve this is by using the urlencode() function to encode any dynamic data that is included in the URL.

// Assuming $row is the result of a database query
$id = $row['id'];
$name = $row['name'];

// Encode the dynamic data for the URL
$id = urlencode($id);
$name = urlencode($name);

// Generate the URL with the encoded data
$url = "http://example.com/page.php?id=$id&name=$name";

// Output the URL
echo $url;