It's all a variation on the same theme:
$bar = "O'Reilly";
"foo = '$bar'"; // foo = 'O'Reilly' -> invalid syntax
Blindly concatenating strings together may lead to syntax violations if the strings are supposed to follow a special syntax. At best this is an annoyance, at worst a security problem. Escaping values prevents these problems. Generic example:
"foo = '" . escape($bar) . "'"; // foo = 'O\'Reilly'
All the different functions are escaping values properly for different syntaxes:
htmlentities
for escaping output for HTML.
mysql_real_escape_string
for escaping values for SQL queries.
addslashes
… not really good for anything, don't use.
json_encode
for encoding/escaping/converting values for Javascript format.