我有一个变量$tekst
,它是一个字符串。我想将该变量保存到mssql数据库。我使用mssql库。这一切都运行良好,直到我有一个像ë é ä á
这样的特殊字符的字符串,然后它会保存它ë é ä á
这是我使用的代码:
$tekst = htmlspecialchars($_POST['tekst']);
$mssql = new Mssql();
$mssql->connect();
$mssql->query("UPDATE siteteksten
SET Siteteksten_Nl='$tekst'
WHERE Sitetekst_Id=$id");
header('Location:'.$_SERVER['HTTP_REFERER']);exit();
列Siteteksten_Nl
的数据类型为nvarchar
和here我发现nvarchar有UCS-2
字符集,所以我添加了
$tekst = mb_convert_encoding( $tekst, 'UCS-2', mb_detect_encoding($tekst, mb_detect_order(), true) );
但现在数据即使没有像ë é ä á
之类的特殊字符也不会执行。它返回此错误消息:
Array ( [0] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 105 [code] => 105 [2] => [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Unclosed quotation mark after the character string ''. [message] => [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Unclosed quotation mark after the character string ''. ) [1] => Array ( [0] => 42000 [SQLSTATE] => 42000 [1] => 102 [code] => 102 [2] => [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near ''. [message] => [Microsoft][ODBC Driver 11 for SQL Server][SQL Server]Incorrect syntax near ''. ) )
有人能看到我在这里失踪的东西吗?
这是Mssql类
class Mssql {
private $username = 'username';
private $password = 'password';
private $db = 'database';
private $server = 'server';
private $conn;
public function connect() {
ini_set('mssql.charset', 'UTF-8');
$this->conn = mssql_connect($this->server, $this->username, $this->password);
mssql_select_db($this->db);
if (!$this->conn) {
die("Connection could not be established.<br> Linux <br>");
}
}
public function query($sql, $return_message=true) {
$query = mssql_query($sql, $this->conn);
// Did the query fail?
if (!$query && $return_message=true) {
return mssql_get_last_message();
}
// Fetch the row
if (!mssql_num_rows($query)) {
return 'No records found';
} else {
$rows = [];
while ($row = mssql_fetch_array($query, MSSQL_BOTH)) {
array_push($rows, $this->encode_items($row) );
}
return $rows;
}
}
public function num_rows($sql) {
$query = mssql_query($sql);
// Did the query fail?
if (!$query) {
die('MSSQL error: ' . mssql_get_last_message());
}
return mssql_num_rows($query);
}
public function encode_items($array) {
foreach($array as $key => $value) {
if(is_array($value)) {
$array[$key] = encode_items($value);
}
else {
$array[$key] = mb_convert_encoding($value, "UTF-8", "ASCII");
}
}
return $array;
}
}
更新:
我找到了解决方案。首先,我在utf8_decode
变量上调用了$tekst
函数,而不是在查询中放置了一个N之前的字符串。
$tekst = utf8_decode($tekst);
$mssql->query("UPDATE siteteksten SET $taal=N'$tekst' WHERE Sitetekst_Id=$id");