In what scenarios should urlencode() or rawurlencode() be used when working with URLs retrieved from a MySQL database in PHP?

When working with URLs retrieved from a MySQL database in PHP, it is important to properly encode the URLs to ensure they are valid and can be safely included in HTML output. The urlencode() or rawurlencode() functions should be used to encode special characters in the URL, such as spaces or symbols, to prevent issues with URL parsing and potential security vulnerabilities.

// Retrieve URL from MySQL database
$url = "https://www.example.com/page with spaces.php?param=value";

// Encode the URL using urlencode()
$encoded_url = urlencode($url);

// Output the encoded URL
echo $encoded_url;