How to escape strings in SQL Server using PHP?

前端 未结 14 1512
我寻月下人不归
我寻月下人不归 2020-11-22 09:36

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

14条回答
  •  失恋的感觉
    2020-11-22 09:47

    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.

    EDIT: There are plenty of issues with that code snippet above. Please don't use this without reading the comments to know what those are. Better yet, please don't use this at all. Parameterized queries are your friends: http://php.net/manual/en/pdo.prepared-statements.php

提交回复
热议问题