PHP 連結 Oracle DB




Server:Oracle Enterprise Linux 5 up4 32bit

Oracle :Oracle 10g Xe

Module: oci8.so

前言:

    oci8模組是利用Oracle Instant Client來進行對Oracle DB之連接,所以如果沒有事先安裝Oracle Instant Client 或 Oracle Database,請先依說明文件將其安裝上去。

1、安裝Linux時已經將PHP 5 一併安裝上去,但是沒有安裝Oracle Link Moduel。

2、先檢查是否有安裝PHP外掛模組編譯命令 phpize,此為PHP Developer的元件之一。

     # rpm -qa |grep php-devel

3、如果找不到php-devel-5.1.6-23.2.el5_3,請將安裝光碟上之套件安裝進去,檔案預設存放於 /usr/bin/phpize 。

    # rpm -ivh php-devel-5.1.6-23.2.el5_3.i386.rpm

4、從Oracle官方網站或PCEL上下載oci8-1.4.1.tgz,並將其解壓縮。

    # tar -zxvf oci8-1.4.1.tgz

5、編譯oci8

    # export ORACLE_HOME=[ORACLE HOME PATH]

    # cd oci8-1.4.1

    # phpize

    # ./configure --with-oci8=$ORACLE_HOME

    # make install

    安裝使用者不一定要是oracle,最好用root,以免權限不足

    預設會把oci8.so放到PHP模組內,如果沒有,請手動複製oci8.so至相關目錄

6、修改PHP.INI

    加入 extension=oci8.so,這裡不必使用絕對路徑,因為路徑已經被指令為 extension_dir = "/usr/lib/php/modules"

7、修改Apache變數,讓Apache可以認得$ORACLE_HOME

    因為Apache會使用apache這個user來執行WEB,但是apache並沒有設定$ORACLE_HOME,所以會產生錯誤

    將$ORACLE_HOME之環境變數加入/etc/init.d/httpd 或 /usr/sbin/apachectl 腳本之內

8、重新啟動Apache

    # service httpd restart

9、測試,範本如下:

   

           $conn = oci_connect('oratest', 'oracle', '192.168.5.16/XE');
           if (!$conn) {
               $e = oci_error();
               trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
           }

           // Prepare the statement
           $stid = oci_parse($conn, 'SELECT * FROM test01');
           if (!$stid) {
               $e = oci_error($conn);
               trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
           }

           // Perform the logic of the query
           $r = oci_execute($stid);
           if (!$r) {
               $e = oci_error($stid);
               trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR);
           }

            // Fetch the results of the query
            print "
\n";
            while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
                print "
\n";
                foreach ($row as $item) {
                    print "  
\n";
               }
               print "
\n";
            }
            print "
            " . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "

\n";
            oci_free_statement($stid);
            oci_close($conn);

    ?>


後記

    一開始安裝完oci8後,因為沒有打開debug模式,因此無法看到錯誤,此時修改php.ini,將display_errors改為on

    ,就可以看見錯誤。接著用phpinfo()來查看PHP的相關設定,發現OCI8已經啟動了,但是測試還是失敗。

    雖然看到錯誤,也知道可能是$ORACLE_HOME沒有設定好,但是改了root及oracle兩個使用者的變數後,仍是

    失敗,最後在google的協助下,找到一個測試的方法,結果發現是Apache不認得$ORACLE_HOME。

    測試範本如下:

         
               $ORACLE_HOME = getenv("ORACLE_HOME");
               echo "ORACLE_HOME=$ORACLE_HOME";
          ?>

Windows 11安裝時跳過網路連線