user2520217
user2520217

Reputation: 309

How to update the Unicode data into SQL Server by PHP?

I using sqlsrv driver to connect the Microsoft SQL Sever 2008 R2 by PHP. But, i tried to update the information by update statement. it doesn't work It seems that i cannot update the information with non-English words. Such as Chinese word. The database doesn't updated.

It works.

$query="UPDATE [Management].[dbo].[Employee]
   SET [Management].[dbo].[Employee].[name] = 'abc'
 WHERE [Management].[dbo].[Employee].[EmpID]=1;";
$stmt=sqlsrv_query( $conn, $query);

It not work.

$query="UPDATE [Management].[dbo].[Employee]
   SET [Management].[dbo].[Employee].[name] = '你好'
 WHERE [Management].[dbo].[Employee].[EmpID]=1;";
$stmt=sqlsrv_query( $conn, $query);

Upvotes: 2

Views: 3006

Answers (2)

Simone Nigro
Simone Nigro

Reputation: 4887

use N flags (nvarchar, ntext...) in table field type for unicode support, and add N flag on query

$query = "UPDATE [Management].[dbo].[Employee]
          SET [Management].[dbo].[Employee].[name] = N'你好'
          WHERE [Management].[dbo].[Employee].[EmpID]=1;";

$stmt = sqlsrv_query($conn, $query);

In html page use charset utf8

<meta http-equiv="Content-Type" content="text/html; charset=utf-8">

Upvotes: 1

M.Ali
M.Ali

Reputation: 69514

Whenever Dealing with Unicode Characters in Sql Server you need to prefix your passed strings with N to tell sql server that passed string can contain some unicode characters ..

For example

DECLARE @Table TABLE (Column1 NVARCHAR(1000))

INSERT INTO @Table VALUES
(N'你好')  -- With N Prefix
,('你好')  -- Without N Prefix

SELECT * FROM @Table

╔═════════╗
║ Column1 ║
╠═════════╣
║ 你好     ║  -- With N Prefix
║ ??      ║  -- Without N Prefix
╚═════════╝

Similarly when you are updating you will need to prefix the string with N something like this

UPDATE [Management].[dbo].[Employee]
   SET [name] = N'你好'
 WHERE [EmpID]=1;

Upvotes: 1

Related Questions