php MsSql server时遇到的中文编码问题 |
||||||||||||||||||||||||||||||||||||||||||||||||
但导到sqlserver 2005后,发现其中文编码只支持GB 和 UCS-2(unicode 16),所以直接在数据库中查询显示正确,但使用php的utf9编码显示时则全是乱码 。 找了大量资料,什么使用mssql,freetds,odbc,ado或直接每次查询和写入都进行转码等建议都有 。不过实际测试中,发现Ado这种方法是好用的 。 代码如下: 复制代码 代码如下: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <?php //print("The next line generates an error.<br>"); //printaline("PLEASE?"); //print("This will not be displayed due to the above error."); ?> <?php $conn = new COM("ADODB.Connection", NULL, CP_UTF8) or die("Cannot start ADO"); //access 数据库的打开方式 //$conn->Open("Provider=Microsoft.Jet.OLEDB.4.0; Data Source=$db"); //$conn->Open("DRIVER={Microsoft Access Driver (*.mdb)}; DBQ=$db"); $conn->Open("Driver={SQL Server};Server={192.168.22.40};Database=sugarcrm_db;UID=sa;PWD=123456;") ; // 执行查询并输出数据 $rs = $conn->Execute(SELECT * FROM accounts) or die ("error query"); ?> <table border="1"> <tr><th>ID</th><th>Title</th> </tr> <?php while (!$rs->EOF) { echo <tr>; echo <td>. $rs->Fields[id]->Value .</td>; echo <td>. $rs->Fields[name]->Value .</td>; echo </tr>; $rs->MoveNext(); } ?> </table> <?php // 释放资源 $rs->Close(); $conn->Close(); $rs = null; $conn = null; ?> </body> </html> 查询结果(与使用sql server managment studio效果一样):
其中,23 ID的编码是GB2312的,其余是utf-8的 。 而使用odbc则跟使用mssql_connect效果一样 。 复制代码 代码如下: <html> <head> <meta http-equiv="Content-Type" content="text/html; charset=utf-8"> </head> <body> <?php //print("The next line generates an error.<br>"); //printaline("PLEASE?"); //print("This will not be displayed due to the above error."); ?> <?php //$conn = odbc_pconnect("myodbc", "sa", "cvttdev", 0); //$connstr="DRIVER=Microsoft Access Driver (*.mdb);DBQ=".realpath("mydb.mdb"); $connstr="Driver={SQL Server};Server={192.168.22.40};Database=sugarcrm_db;UID=sa;PWD=123456;"; $connid=odbc_connect($connstr,"sa","cvttdev",SQL_CUR_USE_ODBC ); $query=odbc_do($connid,"select id,name from accounts"); ?> <table border="1"> <tr><th>ID</th><th>Title</th> </tr> <?php while(odbc_fetch_row($query)) { echo <tr>; $name = odbc_result($query,2); $id=odbc_result($query,1); echo <td>. $id .</td>; echo <td>. $name .</td>; echo </tr>; } ?> </table> 查询结果:
因为odbc 也没有设置内码页的地方 。 |