Exporting data to a .sql format. How to escape?
The reason the MySQL functions require a connection in order to escape the string is that all mysql_real_escape_string()
does is make a call to MySQL's built-in escaping function.
However, if you read the manual page for it, you'll see that they do list the characters which are escaped:
mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which prepends backslashes to the following characters: \x00, \n, \r, \, ', " and \x1a.
You don't want to use addslashes()
since that only escapes a few characters, and would not provide a secure solution. But you should be able to re-implement the escaping done by mysql_real_escape_string()
using the list of characters given, with a simple call to strtr()
or similar:
$replacements = array("\x00"=>'\x00', "\n"=>'\n', "\r"=>'\r', "\\"=>'\\\\', "'"=>"\'", '"'=>'\"', "\x1a"=>'\x1a');$escaped = strtr($unescaped,$replacements);
just a thought, is it possible for you app to generate and sql like
INSERT INTO table1 (id, name) VALUES (?, ?);
and pass a set of paramaters for the sql as an array
$parms = array('value1', 'value2');
and then have the part of your app that does do database work do the escaping at that point
function writeToDb($sql, $parms) {// do escaping here}