php insert Chinese into sqlserver 2008

  • 2020-05-19 04:22:24
  • OfStack

Today, when using php to operate the database, I found that the Chinese field inserted into SQL Server 2008 database was garbled. Here are some situations when I started 1:

The development environment is php5.3.3 + Apache2.2.17 + SQL Server 2008. The code of php script file is utf-8, and the code sent to the database is GB2312 (the default character code of SQL Server may be this, I'm not sure). I used the SQLSRV library provided by Microsoft to connect to the database (PS: SQL Server 2005 is no longer supported by mssql.dll), so sqlsrv_query($conn, "set names GB2312"); The sql statement reads: insert into Opinion (content) values ('aaa Chinese content ');

Run the sql statement and find that the execution is not successful. Use the sqlsrv_errors() function to output the error message and get the following result:
 
Array ( [0] => Array ( [0] => IMSSP [SQLSTATE] => IMSSP [1] => -46 [code] => -46 [2] => An error occurred translating the query string to UTF-16: �ڶ��ֽڵ�Ŀ�����ҳ� У �û� д � Unicode �ַ����ӳ�䵽���ַ� . [message] => An error occurred translating the query string to UTF-16: �ڶ��ֽڵ�Ŀ�����ҳ� У �û� д � Unicode �ַ����ӳ�䵽���ַ� . ) ) 

This is the result displayed on the web page, where the garbled code was left intact by copy. It can be seen from "An error occurred translating the query string to UTF-16" that there was a problem with the character encoding conversion. So I used the iconv function of php to force the encoding conversion of Chinese, and then executed the sql statement. The code is as follows:
 
$string = iconv('utf-8', 'GB2312//IGNORE', 'aaa Chinese content '); 
$sql = "insert into Opinion (content) values ( $string)"; 
[code] 
 The error message is as follows:  
[code] 
Array ( [0] => Array ( [0] => 42S22 [SQLSTATE] => 42S22 [1] => 207 [code] => 207 [2] => [Microsoft][SQL Server Native Client 10.0][SQL Server]���� 'aaa��������' �� Ч �� [message] => [Microsoft][SQL Server Native Client 10.0][SQL Server]���� 'aaa��������' �� Ч �� ) ) 

This error message doesn't make any sense, so I output sql statement to the web page to see if 1 is wrong with sql statement. The output result is as follows:
 
insert into Opinion (content) values ( aaa��������) 

I noticed that the parameter in the following parentheses should be enclosed in quotation marks (indicating that it is a string), so I modified sql statement again. The code is as follows:
 
$sql = "insert into Opinion (content) values ( '".$string."')";  Let me zoom in just to get a good view  


Enclose $string in single quotation marks, so that the sql statement can be executed successfully, and the Chinese characters saved in the database are not scrambled.

Related articles: