使用PHP在SQL Server中转义字符串

时间:2017-02-03 15:13:52

标签: php sql-server

每当我实现this代码时,我在使用单引号时不再出错,但是hexstring get被写入数据库而不是转换回原始字符。

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

这就是我想要做的。 $ suggestTest是我正在使用转义函数的变量。

$nomDept = $_POST['nomDept'];
$subSupervisor = $_POST['subSupervisor'];
$suggestion = $_POST['suggestion'];

$suggestTest = mssql_escape($suggestion);

if ($subSupervisor == "Yes") {
    $query = "INSERT INTO dbo.emp_recog (nomDept, nomSuggestion, subSupervisor) VALUES (";
    $query .= "'" . $nomDept . "', ";
    $query .= "'" . $suggestTest . "', ";
    $query .= "'" . $subSupervisor . "');";
    $res = mssql_query($query);
}

我也尝试省略变量周围的单引号,如此

if ($subSupervisor == "Yes") {
    $query = "INSERT INTO dbo.emp_recog (nomDept, nomSuggestion, subSupervisor) VALUES (";
    $query .= "'" . $nomDept . "', ";
    $query .= $suggestTest ", ";
    $query .= "'" . $subSupervisor . "');";
    $res = mssql_query($query);
}

1 个答案:

答案 0 :(得分:-1)

如果使用prepare来构建SQL语句,则不需要转义变量。