I am passing a variable to a function that executes a query
The MySQL connection only occurs inside the function, and closes inside the function
I want to be able to safely escape strings BEFORE I send them to the function
I can't use mysql_real_escape_string because it requires a MySQL connection (which is only being made inside the function)
I know the simple answer would be to escape strings inside the function, but I cannot do this because I need to send some escaped, and some non-escaped parts of a string
For example, I need to run the function like this:
myquery("'" . escape_me("My string") . "'");
Notice I am sending two apostrophe's-- unescaped, with an escaped string inside. For this reason I can't do a blanket mysql_real_escape_string on arguments inside of myquery function.
I found the following code, suggesting that I could use it as an alternative to mysql_real_escape_string:
// escape characters
function escape_me($value) {
$return = '';
for($i = 0; $i < strlen($value); ++$i) {
$char = $value[$i];
$ord = ord($char);
if($char !== "'" && $char !== "\"" && $char !== '\\' && $ord >= 32 && $ord <= 126)
$return .= $char;
else
$return .= '\\x' . dechex($ord);
}
return $return;
}
I do not know if this function is safe from multibyte attacks, but I think I also need to undo the function every time I query
For example, inputting: Testing 3's "OK" is turned into Testing 3x27s x22OKx22 in the database
So my main question is: Do you know if there is another function I can use as an alternative to mysql_real_escape_string that will safely escape characters?