What are the differences between escaping data for HTML output and escaping data for SQL queries in PHP, and why is it important to distinguish between the two?

When escaping data for HTML output in PHP, special characters like <, >, and & should be converted to their respective HTML entities to prevent XSS attacks. On the other hand, when escaping data for SQL queries, special characters like ' and " should be properly escaped to prevent SQL injection attacks. It's important to distinguish between the two because the escaping mechanisms are different for HTML and SQL, and using the wrong method can leave your application vulnerable to security risks.

// Escaping data for HTML output
$htmlOutput = &quot;&lt;script&gt;alert(&#039;XSS attack!&#039;);&lt;/script&gt;&quot;;
$escapedHtmlOutput = htmlspecialchars($htmlOutput, ENT_QUOTES, &#039;UTF-8&#039;);
echo $escapedHtmlOutput;

// Escaping data for SQL queries
$sqlInput = &quot;John&#039;s SQL injection attempt&quot;;
$escapedSqlInput = mysqli_real_escape_string($connection, $sqlInput);
$sqlQuery = &quot;INSERT INTO users (name) VALUES (&#039;$escapedSqlInput&#039;)&quot;;
mysqli_query($connection, $sqlQuery);