How to escape strings in SQL Server using PHP?

I’m looking for the alternative of mysql_real_escape_string() for SQL Server. Is addslashes() my best option or there is another alternative function that can be used?

Edit: Alternative for mysql_error() would also be useful.

  • Upload csv Files Using SQL Server OpenRowSet Function
  • how to check uniqueness (non duplication) of a post in an rss feed
  • SQL Server to Postgresql - Database migration - Tool issues
  • Can I use a SQL Server CTE to merge intersecting dates?
  • Database Connection Error “file in use”
  • Migrate Oracle partitioned tables to SQL Server
  • 13 Solutions collect form web for “How to escape strings in SQL Server using PHP?”

    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);
        INSERT INTO sometable (somecolumn)
        VALUES (0x' . $unpacked['hex'] . ')

    Abstracted, that would be:

    function mssql_escape($data) {
            return $data;
        $unpacked = unpack('H*hex', $data);
        return '0x' . $unpacked['hex'];
        INSERT INTO sometable (somecolumn)
        VALUES (' . mssql_escape($somevalue) . ')

    mysql_error() equivalent is mssql_get_last_message().

    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.

    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.

    Why would you bother escaping anything when you can use parameters in your query?!

        'UPDATE some_table SET some_field = ? WHERE other_field = ?', 
        array($_REQUEST['some_field'], $_REQUEST['id'])

    It works right in selects, deletes, updates regardless whether your values parameters are null or not.
    Make a matter of principle – Don’t concatenate SQL and you are always safe and your queries read much better.

    another way to handle single and double quotes is

    function mssql_escape($str)
        $str= stripslashes($str);
       return str_replace("'", "''", $str);

    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' ) ";


    and attribution: Escape Character In Microsoft SQL Server 2000

    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:

    • Microsoft Drivers 3.0 for PHP for SQL Server (SQLSRV30.EXE): Download and follow the instructions to install.
    • Microsoft® SQL Server® 2012 Native Client: Search through the extensive page for the Native Client. Even though it’s 2012, I’m using it to connect to SQL Server 2008 (installing the 2008 Native Client didn’t worked). Download and install.

    After that you can connect in PHP with PDO using a DSN like the following example:

    sqlsrv:Server=; 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.

    i know, litle bit late, but answer from ‘Feb 22 ’09 at 12:10’ by chaos isn`t fit all queries. E.g:
    “CREATE LOGIN [0x6f6c6f6c6f] FROM WINDOWS” will give you exception

    p.s. look at mssql driver for php, and sqlsrv_prepare function, which can binds params.

    p.s.s. which also didn`t helps you with query above 😉

    If you are using PDO, you can use the PDO::quote method.

    Warning: This function was REMOVED in PHP 7.0.0.

    For anyone still using these mssql_* functions, keep in mind that they have been removed from PHP as of v7.0.0. So, that means you eventually have to rewrite your model code to either use the PDO library, sqlsrv_* etc. If you’re looking for something with a “quoting/escaping” method, I would recommend PDO.

    Alternatives to this function include: PDO::query(), sqlsrv_query() and odbc_exec()

    For the conversion to get the HEX in SQL back into ASCII here is the solution I got on this (using the function from Chaos to encode into Hex)

    function hexEncode($data) {
            return $data;
        $unpacked = unpack('H*hex', $data);
        return '0x' . $unpacked['hex'];
    function hexDecode($hex) {
        $str = '';
        for($i=0;$i<strlen($hex);$i+=2) $str .= chr(hexdec(substr($hex,$i,2)));
        return $str;
    $stringHex = hexEncode('Test String');
    $stringAscii = hexDecode($stringHex);

    I have been using this as an alternative of mysql_real_escape_string():

    $data = "Whatever the value is";
    $data = stripslashes(htmlspecialchars($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.

    MS SQL Server is a Microsoft SQL Database product, include sql server standard, sql server management studio, sql server express and so on.