7

Am wondering what is the equivalent in PHP for SQL Server escaping of strings?

2
  • 3
    If you use a wrapper like PDO, you won't have to worry about that because you can work with parametrized queries. If you can, use a wrapper. Commented Jan 27, 2010 at 11:52
  • Sorry, dont have the privelege to use PDO. Commented Jan 27, 2010 at 11:53

3 Answers 3

7

Nice question, I don't know but you could use PDO::quote() with the PDO_DBLIB driver.


EDIT: Seems like this guy got it from StackOverflow:

function mssql_escape($data) {
    if(is_numeric($data))
        return $data;
    $unpacked = unpack('H*hex', $data);
    return '0x' . $unpacked['hex'];
}

Another option:

function mssql_escape($str)
{
    if(get_magic_quotes_gpc())
    {
        $str= stripslashes($str);
    }
    return str_replace("'", "''", $str);
}
Sign up to request clarification or add additional context in comments.

1 Comment

Does it work with PHP7? Cause they removed it.
3

The best alternative is to use parameterised queries, then you don't have to escape strings.

If you still want to put the query together yourself, the proper way to escape a string literal for SQL Server (T-SQL) is to replace each apostrophe (') in the string with two apostrophes.

3 Comments

Does that also handle null characters, backslashes and the like in the string?
@ebyrob: Yes. Backslashes in a string doesn't need any special treatment at all, by the way.
Is this valid for all character sets?
0

The short answer is: use whatever mechanism your connection libraries provide, it really has nothing to do with the database. If you're using ADO, you have parameterized queries, if you're using something else (I know nothing about PHP) then use whatever that library offers.

Rolling your own is probably a bad idea, because you're very likely to get something wrong, e.g. handling comment delimiters correctly.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.