Greg Ostry
Greg Ostry

Reputation: 1231

How to escape single quotes in php for tsql string (ms sql)

how can i escape the single quotes in stuff function? I'm connecting Microsoft SQL with PHP.

$hcode = $_GET['hcode'];
$sql = "SELECT AB.HCode, STUFF(AB.Name1,1,6, '') FROM Article AB WHERE Mandant=1 AND Language= 'EN' AND HCode= '".$hcode."' AND AB.Name1 IS NOT NULL";
$result = sqlsrv_query($conn, $sql);

Upvotes: 1

Views: 811

Answers (1)

Rahul Gupta
Rahul Gupta

Reputation: 10141

To escape strings with single quotes for MS SQL, we would need to escape it by adding an another single quote.

The following function does this. So, you may try using this function:

public static function mssql_escape($unsafe_str) 
{
    if (get_magic_quotes_gpc())
    {
        $unsafe_str = stripslashes($unsafe_str);
    }
    return $escaped_str = str_replace("'", "''", $unsafe_str);
}
//for example $unsafe = "AB'CD'EF";
$escaped = mssql_escape($unsafe);
echo $escaped;// Would output the escaped string as  "AB''CD''EF"

Upvotes: 1

Related Questions