如何在 PDO OCI 中设置 UTF8 // PHP

How to set UTF8 in PDO OCI // PHP

我想连接我的 Oracle SQL 并且已经设置了 utf8, 但是当我 select 或插入一些东西时仍然出现乱码。

这是我的代码:

define("DB_HOST", "(DESCRIPTION =(ADDRESS = (PROTOCOL=TCP)
                            (HOST= IP)
                            (PORT=1521))
                            (CONNECT_DATA=(SID=IETDB)));
                            charset = utf8
    ");

如何解决这个问题?

您不能通过修改连接字符串来执行此操作,因为它不受支持。

oci_connect 手册页所述,第四个参数指定字符集:

oci_connect($username, $password, $connection_string, 'UTF-8');

这告诉 OCI 希望您提供 UTF8 格式的字符串,并提供从数据库字符集转换而来的 UTF8 格式的结果集。来自手册:

Determines the character set used by the Oracle Client libraries. The character set does not need to match the character set used by the database. If it doesn't match, Oracle will do its best to convert data to and from the database character set. Depending on the character sets this may not give usable results. Conversion also adds some time overhead.

If not specified, the Oracle Client libraries determine a character set from the NLS_LANG environment variable.

Passing this parameter can reduce the time taken to connect.

如果您使用 PDO_OCI 字符集可以附加到 DSN,同样 as documented:

new \PDO('oci:dbname=' . $conn_string . ';charset=UTF8', $username, $password);