Today, when you use PHP to manipulate the database, you find that the Chinese text segment in the SQL Server 2008 database is garbled, and here are some things I started with:
The development environment is the encoding of the Php5.3.3+apache2.2.17+sql Server 2008,php script file is utf-8, the encoding passed to the database is GB2312 (the default character encoding for SQL Server may be this, I'm not sure), I use the Microsoft Official Sqlsrv Library to connect to the database (Ps:sql Server 2005 has not supported the use of Mssql.dll to connect), so the use of sqlsrv_query ($conn, "Set names GB2312"); Statement to set the encoding format passed to the database, the SQL statement reads: INSERT into Opinion (content) VALUES (' AAA Chinese contents ');
Run this SQL statement, find that execution is unsuccessful, use the sqlsrv_errors () function to output the error message, and get the following result:
Copy Code code as follows:
Array ([0] => Array ([0] => IMSSP [SQLSTATE] => IMSSP [1] => -46 [code] => -46 [2] => an error Occurre D translating the query string to Utf-16:ڶֽڵŀҳуûдunicodeַӳ䵽ַ. [Message] => A error occurred translating the query string to Utf-16:ڶֽڵŀҳуûдunicodeַӳ䵽ַ. ) )
This is the results displayed on the Web page, the above garbled is copy down intact. From "An error occurred translating the query string to UTF-16" You can see that there is a problem with the character encoding conversion. So I used PHP's iconv function to force code conversion in Chinese, and then executed the SQL statement, which reads:
Copy Code code as follows:
$string = Iconv (' utf-8 ', ' gb2312//ignore ', ' AAA Chinese content ');
$sql = "INSERT into Opinion (content) VALUES ($string)";
[Code]
This time again, 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 does not see any clue, I also output the SQL statement to the Web page to see if the SQL statement is wrong, the output is as follows:
Copy Code code as follows:
Insert into Opinion (content) VALUES (AAA)
I look like no problem, in fact, there is a problem, notice that the parentheses in the back of the argument should be enclosed in quotation marks (indicating that it is a string), so I modified the SQL statement, the code is as follows:
Copy Code code as follows:
$sql = "INSERT into Opinion (content) VALUES ('. $string."); To see if I can zoom in.
Enclose the $string in single quotes so that the execution of the SQL statement succeeds, and the Chinese in the database are not garbled.