4

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.

Dale K
  • 25,246
  • 15
  • 42
  • 71
Iter Ator
  • 8,226
  • 20
  • 73
  • 164
  • You could use `nvarchar`, that supports full Unicode – Charlieface Mar 29 '21 at 23:40
  • I can not change the column definitions – Iter Ator Mar 30 '21 at 09:30
  • Then what do you expect? These are not PHP errors, SQL Server is telling you that it simply cannot store that data in a `varchar` column with that collation, it is impossible. What exactly was the charset error, and how did it happen (what code causes it)?. – Charlieface Mar 30 '21 at 11:53
  • @Charlieface We used the old `mssql_` functions before, and everything worked well with it. The tables were filled from php using `mssq_`. Now we upgrade to PHP 7, and our only option is PDO with the ODBC SQL Server driver. If I list the contents of that table in SQL Server Management Studio, I can see all the rows without an error. So the error must be with the new driver, but I have no idea how to configure it. – Iter Ator Mar 30 '21 at 12:56

2 Answers2

0

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);
Foramkumar Patel
  • 299
  • 3
  • 10
0

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.

Dmitry Leiko
  • 3,970
  • 3
  • 25
  • 42