When accessing an Access database using PDO_ODBC, non-standard characters may return incorrect values. This article explores the underlying issue and provides a comprehensive solution using COM with ADODB Connection and Recordset objects.
PDO_ODBC does not natively handle UTF-8 encoding for text retrieved from an Access database. This causes a mismatch between the actual character encoding and the encoding assumed by the browser or PHP. As a result, non-standard characters are garbled or displayed incorrectly.
Some attempts to fix the issue involve converting the returned text to UTF-8 using functions like utf8_encode() or mb_convert_encoding(). While these may resolve issues with certain character sets like Windows-1252, they do not fully address the problem for all Unicode characters.
For complete UTF-8 support, it is recommended to use COM with ADODB Connection and Recordset objects. Here's how to implement this solution:
<code class="php">// Connect to the database using ADODB with UTF-8 encoding $con = new COM("ADODB.Connection", NULL, CP_UTF8); $con->Open($connStr); // Open a Recordset and execute the query $rst = new COM("ADODB.Recordset"); $sql = "SELECT Team FROM Teams"; $rst->Open($sql, $con, 3, 3); // adOpenStatic, adLockOptimistic // Iterate through the Recordset and retrieve the characters while (!$rst->EOF) { $s = $rst->Fields("Team"); echo $s . "<br/>\n"; $rst->MoveNext(); } // Close the Recordset and connection $rst->Close(); $con->Close();</code>
By using this approach, all characters will be correctly encoded as UTF-8 and displayed properly.
The above is the detailed content of How to Handle UTF-8 Accented Character Retrieval from Access Database via PDO ODBC?. For more information, please follow other related articles on the PHP Chinese website!