How to escape strings in SQL Server using PHP?

前端 未结 14 1480
我寻月下人不归
我寻月下人不归 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:50

    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().

提交回复
热议问题