问题描述:

I want to store data with PHP in a MS SQL 2008 Database.

I`ve got problems with letters like , they are displayed incorrect in the database and when i display it on the website.

It works when I utf8_encode the data on input and utf8_decode on output the data with PHP.

Is there a other easier way to solve this?

网友答案:

I've solved this once, the problem is that the PHP's mssql driver is broken (can't find the link to bugs.php.net, but it is there) and fails when it comes to nchar and nvarchar fieldsa and utf8. You'll need to convert the data and queries a little bit:

SELECT some_nvarchar_field FROM some_table

First, you need to change the output to binary - that way it won't get corrupted:

SELECT CONVERT(varbinary(MAX), some_nvarchar_field) FROM some_table;

Then in PHP, you'll need to convert it to UTF-8 back, there you'll need iconv extension

iconv('UTF-16LE', 'UTF-8', $result['some_nvarchar_field']);

This fixes selectiong data from database, however, if you want to actually put some data TO the database, or add a WHERE clause, you'll still be getting errors, so the fix for WHERE, UPDATE, INSERT and so on is by converting the string to hexadecimal form: Imagine you have this query:

INSERT INTO some_table (some_nvarchar_field) VALUES ('');

Now, we'll have to run some PHP:

$value = '';
$value = iconv('UTF-8', 'UTF-16LE', $value); //convert into native encoding 
$value = bin2hex($value); //convert into hexadecimal
$query = 'INSERT INTO some_table (some_nvarchar_field)  VALUES(CONVERT(nvarchar(MAX), 0x'.$value.'))'; 

The query becomes this:

INSERT INTO some_table (some_nvarchar_field) VALUES (CONVERT(nvarchar(MAX), 0x7d010c0158011a01dd00c100d600));

And that will work!

I've tested this with MS SQL server 2008 on Linux using FreeTDS and it works just fine, I've got some huge websites runing on this with no issues what so ever.

网友答案:

I searched for two days how to insert UTF-8 data (from web forms) into MSSQL 2008 through PHP. I read everywhere that you can't, you need to convert to UCS2 first (like cypher's solution recommends). On Windows environment SQLSRV said to be a good solution, which I couldn't try, since I am developing on Mac OSX.

However, FreeTDS manual (what PHP mssql uses on OSX) says to add a letter "N" before the opening quote:

mssql_query("INSERT INTO table (nvarcharField) VALUES (N'')", +xon);

According to this discussion, N character tells the server to convert to Unicode. http://programmers.stackexchange.com/questions/155859/why-do-we-need-to-put-n-before-strings-in-microsoft-sql-server

相关阅读:
Top