Define encoding when using PDO ODBC SQL Server connection?

Viewed 303

I connect to a SQL Server using like this:

$pdo = new PDO("odbc:DRIVER=ODBC Driver 17 for SQL Server;SERVER=$serverName;DATABASE=$dbName", $username, $password);

The PDO instance is created, and I can run SQL queries with it, but sometimes I get charset related errors.

The database collation is non unicode (latin2), and I would like to get the response in UTF8. How is it possible to define it?

I was able to find some parameters like PDO::MYSQL_ATTR_INIT_COMMAND => "SET NAMES ..." but those are not available here, because I have an SQL Server.

2 Answers

you have to try as below to add Client_CSet=UTF-8; to your connection code.

$pdo = new PDO("odbc:DRIVER=ODBC Driver 17 for SQL Server;SERVER=$serverName;DATABASE=$dbName;Client_CSet=UTF-8;Server_CSet=Windows-1251", $username, $password);

Only you need add charset=utf8 in dns varible. You can try this configuration:

$dns = "odbc:DRIVER=ODBC Driver 17 for SQL Server;SERVER=$serverName;DATABASE=$dbName;charset=utf8"

$pdo = new PDO($dns, $username, $password);

Similar question. Hope help you.

Related