I'm looking for the alternative of mysql_real_escape_string()
for MSSQL. Is addslashes()
my best option or there is another alternative function that can be used?
Edit: Alternative for mysql_error()
would also be useful.
I'm looking for the alternative of mysql_real_escape_string()
for MSSQL. Is addslashes()
my best option or there is another alternative function that can be used?
Edit: Alternative for mysql_error()
would also be useful.
You could look into the PDO Library. You can use prepared statements with PDO, which will automatically escape any bad characters in your strings if you do the prepared statements correctly. This is for PHP 5 only I think.
addslashes() is not as good as mysql_real_escape_string() as the latter escapes a few extra bad characters if I recall correctly.
addslashes() isn't fully adequate, but PHP's mssql package doesn't provide any decent alternative. The ugly but fully general solution is encoding the data as a hex bytestring, i.e.
$unpacked = unpack('H*hex', $data);
mssql_query('
INSERT INTO sometable (somecolumn)
VALUES (0x' . $unpacked['hex'] . ')
');
Abstracted, that would be:
function mssql_escape($data) {
if(is_numeric($data))
return $data;
$unpacked = unpack('H*hex', $data);
return '0x' . $unpacked['hex'];
}
mssql_query('
INSERT INTO sometable (somecolumn)
VALUES (' . mssql_escape($somevalue) . ')
');
mysql_error() equivalent is mssql_get_last_message().
You could roll your own version of mysql_real_escape_string
, (and improve upon it) with the following regular expression: [\000\010\011\012\015\032\042\047\134\140]
. That takes care of the following characters: null, backspace, horizontal tab, new line, carriage return, substitute, double quote, single quote, backslash, grave accent. Backspace and horizontal tab are not supported by mysql_real_escape_string
.
function ms_escape_string($data) {
if ( !isset($data) or empty($data) ) return '';
if ( is_numeric($data) ) return $data;
$non_displayables = array(
'/%0[0-8bcef]/', // url encoded 00-08, 11, 12, 14, 15
'/%1[0-9a-f]/', // url encoded 16-31
'/[\x00-\x08]/', // 00-08
'/\x0b/', // 11
'/\x0c/', // 12
'/[\x0e-\x1f]/' // 14-31
);
foreach ( $non_displayables as $regex )
$data = preg_replace( $regex, '', $data );
$data = str_replace("'", "''", $data );
return $data;
}
Some of the code here was ripped off from CodeIgniter. Works well and is a clean solution.