This function is used to create a legal SQL string that you can use in an
SQL statement. The given string is encoded to an escaped SQL string,
taking into account the current character set of the connection.

Caution

Security: the default character set

The character set must be set either at the server level, or with
the API function mysqli_set_charset() for it to affect
mysqli_real_escape_string(). See the concepts section
on character sets for
more information.

You can avoid all character escaping issues (on the PHP side) if you use prepare() and bind_param(), as an alternative to placing arbitrary string values in SQL statements. This works because bound parameter values are NOT passed via the SQL statement syntax.

A PHP application I'm working on has many pages which (long story) need to share a PHP API that looks after a MySQL database. Easiest way was to have the app pages AJAX to the API .PHPs.

That means having the JavaScript of the AJAX encodeURIComponent(...) relevant bits of any data to be sent via HTTP POST and GET requests - space as %20 and so on.

But the SQL also needed real_escape_string(...) of the same data.

So I had the issue of whether to do the real_escape_string *before* or *after* encodeURIComponent? in other words in the application PHP or API PHP? Do either of the encodings mangle the other?

The real_escape_string would be "cleaner" in the API, both in principle, and because it needs an instance of mysqli class and there are are unlikely to be instances in the app.

(real_escape_string needs an instance because it's not a *static* function - I don't know why).

But I suspect that "in the API" is the mangle-avoiding place: the JavaScript encode gets undone by the HTTP call to whichever API element, then the element can safely real_escape_string what is to be put into the database.