character encoding puzzle with PHP/MS Access

蹲街弑〆低调 提交于 2019-12-24 10:46:08

问题


NB This is MS Access 2000, and this PHP file is called with an ajax call...

At the start of this PHP file I have put

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

The $token below comes from these lines

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

This works OK when I have a "token" without French accented characters:

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

But although the SQL with a French word like "référé" looks fine (like this):

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

unfortunately the query returns 0 rows... even though there are records it should return... so it seems likely to me that character encoding has got to be the problem

NB I also tried encoding using utf8_encode but this, as was pointed out, makes no sense and garbled the SQL string...


回答1:


This is the PHP code I got working. I had to use mb_convert_encoding(), which is part of the PHP "Multibyte String" ("mbstring") extension.

The code:

<?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);

The result when run from the Windows command line:

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
        )

)

Note that the command-line output itself is slightly garbled, but at least the SQL query returned a result....



来源:https://stackoverflow.com/questions/16233795/character-encoding-puzzle-with-php-ms-access

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!