简体   繁体   中英

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);

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"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM