PHP + SQL Server - How to set charset for connection?

前端 未结 13 1003
借酒劲吻你
借酒劲吻你 2020-12-01 06:54

I\'m trying to store some data in a SQL Server database through php.

Problem is that special chars aren\'t converted properly. My app\'s charset is iso-8859-1 and th

相关标签:
13条回答
  • 2020-12-01 07:10

    You can use the mysql_set_charset function: http://it2.php.net/manual/en/function.mysql-set-charset.php

    0 讨论(0)
  • 2020-12-01 07:13

    I had the same problem and ini_set('mssql.charset', 'utf-8') did not work for me. However, it worked in uppercase:

    ini_set('mssql.charset', 'UTF-8');
    
    0 讨论(0)
  • 2020-12-01 07:13

    If you are using TDS protocol version 7 or above, ALL communications over the wire are converted to UCS2. The server will convert from UCS2 into whatever the table or column collation is set to, unless the column is nvarchar or ntext. You can store UTF-8 into regular varchar or text, you just have to use a TDS protocol version lower than 7, like 6.0 or 4.2. The only drawback with this method is that you cannot query any nvarchar, ntext, or sys.* tables (I think you also can't do any CAST()ing) - as the server refuses to send anything that might possibly be converted to UTF-8 to any client using protocol version lower than 7.

    It is not possible to avoid converting character sets when using TDS protocol version 7 or higher (roughly equivalent to MSSQL 2005 or newer).

    0 讨论(0)
  • 2020-12-01 07:13

    If ini_set('mssql.charset', 'UTF-8'); doesn't help AND you don't have root access to modify the system wide freetds.conf file, here's what you can do:

    1. Set up /your/local/freetds.conf file:

    [sqlservername]
        host=192.168.0.56
        port=1433
        tds version=7.0
        client charset=UTF-8
    

    2. Make sure your connection DSN is using the servername, not the IP:

    'dsn' => 'dblib:host=sqlservername;dbname=yourdb
    

    3. Make FreeTDS to use your local freetds.conf file as an unprivileged user from php script via env variables:

    putenv('FREETDSCONF=/your/local/freetds.conf');
    
    0 讨论(0)
  • 2020-12-01 07:13

    Can't you just convert your tables to your application encoding? Or use utf-8 in both?

    I don't know whether MSSQL supports table-level encodings, though.

    Also, try the MB (multibyte) string functions, if the above fails.

    0 讨论(0)
  • 2020-12-01 07:16

    I've had luck in a similar situation (using a PDO ODBD connection) using the following code to convert the encoding before printing output:

    $data = mb_convert_encoding($data, 'ISO-8859-1', 'windows-1252');
    

    I had to manually set the source encoding, because it was erroneously being reported as 'ISO-8859-1' by mb_detect_encoding().

    My data was also being stored in the database by another application, so I might be in a unique situation, although I hope it helps!

    0 讨论(0)
提交回复
热议问题