July 13, 2010 | In: Coding Tips

MSSQL query escape in PHP

PHP supports mysql_escape_string but if you use PHP with MSSQL you need to use your own method. Here’s the code snippet to escape characters. A better solution than using addslashes.

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;
}

Comment Form

Categories

Calendar

September 2010
M T W T F S S
« Aug    
 12345
6789101112
13141516171819
20212223242526
27282930