PHP / MS Access的字符编码难题

时间:2013-04-26 10:03:59

标签: php sql ms-access character-encoding

注意这是MS Access 2000,使用ajax调用调用此PHP文件...

在这个PHP文件的开头我放了

ini_set('default_charset', 'utf-8');

以下$令牌来自这些行

$search_string = $_GET[ 'search_string' ];
$search_tokens = explode( " ", $search_string );
$token = $search_tokens[ 0 ];

当我有一个没有法语重音字符的“标记”时,这个工作正常:

$sql="SELECT * FROM tblFrEng WHERE French = '$token'";
echo "=== SQL is $sql<br>";
$sth = $dbh->prepare( $sql );
$sth->execute();

但是,虽然带有像“référé”这样的法语单词的 SQL 看起来很好(就像这样):

=== SQL is SELECT * FROM tblFrEng WHERE French = 'référé'

不幸的是,查询返回0行...即使有记录它应该返回...所以我觉得字符编码必须是问题

NB我也尝试使用utf8_encode进行编码,但正如所指出的那样,没有任何意义并且使SQL字符串乱码......

1 个答案:

答案 0 :(得分:0)

这是我工作的PHP代码。我不得不使用mb_convert_encoding(),这是PHP“Multibyte String”(“mbstring”)扩展的一部分。

代码:

<?php
// NB: save this PHP script as an ANSI text file, not a UTF-8 encoded file

$dbh = new PDO(
        'odbc:Driver={Microsoft Access Driver (*.mdb)};' .
        'Dbq=C:\\Users\\Public\\acc2000.mdb;' .
        'Uid=Admin;Pwd=;');

// this is our test case
$city = 'Montréal';
echo '$city: ' . $city . "\r\n";

// this is the UTF-8 "token" we'd get from the AJAX call...
$token = utf8_encode($city);
echo '$token: ' . $token . "\r\n";

// ...and here we convert to the Access_2000 character set
$win_token = mb_convert_encoding($token, 'Windows-1252', 'UTF-8');
echo '$win_token: ' . $win_token . "\r\n";

$sth = $dbh->prepare('SELECT * FROM Cities WHERE City = ?');
$sth->Execute(array($win_token));
$rst = $sth->fetchAll();
echo '$rst: ';
print_r($rst);

从Windows命令行运行时的结果:

C:\__tmp>\php\php odbcTest.php
$city: MontrΘal
$token: Montréal
$win_token: MontrΘal
$rst: Array
(
    [0] => Array
        (
            [City] => MontrΘal
            [0] => MontrΘal
        )

)

请注意,命令行输出本身略有乱码,但至少SQL查询返回了结果....