Thursday, November 20, 2008

Escape Character in MSSQL

I had a frustrating time trying to escape single quotes in MSSQL.  I had enclosed my content in single quotes so that double quotes would be okay, but then I had to deal with if a user put a single quote in the field.  In standard MySQL you could just use the backslash (\) but MSSQL requires a single quote (') in order to escape a character!

Here is a little function I made in PHP to look for single quotes and doubling them so that they would be escaped (thus allowing the content to be inserted into MSSQL).

//********************************
// fix quotes for mssql
//********************************
function mssql_quote_fix($text)
{
$text = str_replace("'", "''", $text);
return $text;
}

Just call this function on the text you're trying to insert.

I'll give a little credit to this article for helping me: Escape Character In Microsoft SQL Server 2000

No comments: