I\'m looking for the alternative of mysql_real_escape_string()
for SQL Server. Is addslashes()
my best option or there is another alternative funct
I have been using this as an alternative of mysql_real_escape_string()
:
function htmlsan($htmlsanitize){
return $htmlsanitize = htmlspecialchars($htmlsanitize, ENT_QUOTES, 'UTF-8');
}
$data = "Whatever the value's is";
$data = stripslashes(htmlsan($data));
In order to escape single- and double-quotes, you have to double them up:
$value = 'This is a quote, "I said, 'Hi'"';
$value = str_replace( "'", "''", $value );
$value = str_replace( '"', '""', $value );
$query = "INSERT INTO TableName ( TextFieldName ) VALUES ( '$value' ) ";
etc...
and attribution: Escape Character In Microsoft SQL Server 2000
If you are using PDO, you can use the PDO::quote method.
It is better to also escape SQL reserved words. For example:
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
'/\27/'
);
foreach ($non_displayables as $regex)
$data = preg_replace( $regex, '', $data);
$reemplazar = array('"', "'", '=');
$data = str_replace($reemplazar, "*", $data);
return $data;
}
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
.
After struggling with this for hours, I've come up with a solution that feels almost the best.
Chaos' answer of converting values to hexstring doesn't work with every datatype, specifically with datetime columns.
I use PHP's PDO::quote()
, but as it comes with PHP, PDO::quote()
is not supported for MS SQL Server and returns FALSE
. The solution for it to work was to download some Microsoft bundles:
After that you can connect in PHP with PDO using a DSN like the following example:
sqlsrv:Server=192.168.0.25; Database=My_Database;
Using the UID
and PWD
parameters in the DSN didn't worked, so username and password are passed as the second and third parameters on the PDO constructor when creating the connection.
Now you can use PHP's PDO::quote()
. Enjoy.