This is because mysql_real_escape_string takes into account the current connection character set. So he needs a connection. :-)
If you do not want to manually configure the connection in advance, you can set various MySQL runtime values in your .ini file.
However, if you use your own database class (or just manual commands), it is often worthwhile to establish a connection throughout the life of your script.
source share