PHP 5.x PDO 連結 Oracle for CentOS 7

說明如何在 CentOS 7 PHP 5.x 版本,建置 PDO 連結 Oracle 資料庫的環境教學。


安裝 Oracle 驅動

Oracle 依要連線的資料庫版本下載符合軟體(須註冊登入才可下載):

  • Oracle 9i 及以上,需要 Instant Client 11 或以下
  • Oracle 8 和 8i ,需要 Instant Client 10 或以下(小傑用的版本)

下載檔案 oracle-instantclient-basic-10.2.0.5-1.x86_64.rpmoracle-instantclient-devel-10.2.0.5-1.x86_64.rpm

安裝:

[root@localhost ~]# rpm -Uvh oracle-instantclient-basic-10.2.0.5-1.x86_64.rpm
[root@localhost ~]# rpm -Uvh oracle-instantclient-devel-10.2.0.5-1.x86_64.rpm

安裝相關套件

安裝:

[root@localhost ~]# yum install php-pear php-devel gcc git

安裝 OCI

透過 OCI(Oracle Call Interface)來與 Oracle 資料庫連結。預設安裝的 oci8,版本須為 PHP 7,因此無法順利安裝:

[root@localhost ~]# pecl install oci8
WARNING: channel "pecl.php.net" has updated its protocols, use "pecl channel-update pecl.php.net" to update
pecl/oci8 requires PHP (version >= 7.0.0), installed version is 5.6.30
No valid packages found
install failed

必須指定安裝的 oci8 版本,才可順利安裝:

[root@localhost ~]# pecl install oci8-2.0.12

安裝時如遇到提示以下錯誤:

... 以上省略 ...
In file included from /local/users/appadmin/oci8-2.0.8/oci8.c:46:
/local/users/appadmin/oci8-2.0.8/php_oci8_int.h:48:29: error: oci8_dtrace_gen.h: No such file or directory
make: *** [oci8.lo] Error 1

必須先將該行注解:(參考 php-devel for php56

[root@localhost ~]# vi /usr/include/php/main/php_config.h
/* Defined to 1 if PHP OCI8 DTrace support was enabled during configuration */
/*#define HAVE_OCI8_DTRACE 1*/

PHP 配置設定:

[root@localhost pdo_oci]# echo extension=oci8.so > /etc/php.d/oci8.ini

確認是否安裝完成:

[root@localhost pdo_oci]# php -m | grep -i oci
oci8

安裝 PDO OCI

下載:

[root@localhost ~]# git clone https://github.com/hotta/pdo_oci
[root@localhost ~]# cd pdo_oci/

安裝:

[root@localhost pdo_oci]# phpize
[root@localhost pdo_oci]# ./configure --with-pdo-oci=instantclient,/usr,10.2.0.5
[root@localhost pdo_oci]# make & make install

PHP 配置設定:

[root@localhost pdo_oci]# echo extension=pdo_oci.so > /etc/php.d/pdo_oci.ini

重啟 Web Server:

[root@localhost ~]# systemctl restart httpd

確認是否安裝完成:

[root@localhost pdo_oci]# php -m | grep -i oci
PDO_OCI

其它設置

關閉 SELINUX(因找不到針對 oci 的設定):

[root@localhost ~]# vi /etc/selinux/config
SELINUX=disabled

firewall 允許 1521 port:

[root@localhost ~]# firewall-cmd --permanent --add-port="1521/tcp" --zone="public"
[root@localhost ~]# firewall-cmd --reload

PDO 連線程式

PHP 使用 PDO 連結 Oracle 資料庫。

<?php
// IP 與 PORT
$tns = '
(DESCRIPTION =
    (ADDRESS_LIST =
        (ADDRESS = (PROTOCOL = TCP)(HOST = 192.168.3.1)(PORT = 1521))
    )
    (CONNECT_DATA =
        (SERVICE_NAME = orcl)
    )
)';

$user = 'tnfd';     // 帳號
$passwd = 'tnfd';   // 密碼

try {
    $dbConn = new PDO('oci:dbname=' . $tns, $user, $passwd);
} catch (PDOException $e){
    echo $e->getMessage();
}

$stmt = $dbConn->query('SELECT * FROM BACUST00');
$row = $stmt->fetch();

echo '<pre>';
var_dump($row);
echo '</pr>>';


1 則評論 to “PHP 5.x PDO 連結 Oracle for CentOS 7”

  1. 感謝您的教程。這是非常有用的!!

發表迴響