要想用php連接Oracle,需要:
1.安裝并配置Oracle instant Client
2.配置php的php_oci8_11g拓展
一苍柏、Window
(一)安裝Oracle instant Client
根據(jù)系統(tǒng)和PHP版本信息去Oracle官網(wǎng)下載相應(yīng)的Oracle instant Client版本
右鍵我的電腦,選中屬性-高級(jí)系統(tǒng)設(shè)置-高級(jí)-環(huán)境變量,在Path中加入Oracle instant Client所在的路徑
(二)配置php_oci8_11g拓展
根據(jù)phpinfo()的信息,前往oci8拓展下載相應(yīng)版本的dll玲昧,將下載了的dll放到php的ext目錄,并且在php.ini配置文件中加入extension=php_oci8_11g.dll
篮绿,重啟php,可以通過(guò)命令行調(diào)用php -m
查看模塊是否加載
(三)錯(cuò)誤
1.提示"%1 不是有效的 Win32 應(yīng)用程序"
Oracle instant Client版本有問(wèn)題吕漂,要根據(jù)PHP版本來(lái)確定Oracle instant Client版本亲配,比如雖然系統(tǒng)是64位,但如果PHP是32位的話,那么Oracle instant Client要選用32位的
二吼虎、Linux(redhat6)
(一)下載Oracle instant Client
根據(jù)系統(tǒng)信息去Oracle官網(wǎng)下載相應(yīng)的Oracle instant Client版本犬钢,博主用是的zip包方法,所以下載了相應(yīng)的basic包思灰,即instantclient-basic-linux.x64-12.2.0.1.0.zip玷犹、 SDK包,即instantclient-sdk-linux.x64-12.2.0.1.0.zip
(二)下載php_oci8源碼包
根據(jù)phpinfo()的信息洒疚,前往oci8拓展下載相應(yīng)版本的源碼包歹颓,博主用的是PHP7,因此下載的是oci8-2.1.4.tgz
(三)安裝
將Oracle instant Client的sdk包和basic包解壓到同一目錄油湖,例如我解壓到/opt巍扛,合并成/opt/instantclient_12_2目錄。
[root@rhl6 opt]# unzip instantclient-basic-linux.x64-12.2.0.1.0.zip
[root@rhl6 opt]# unzip instantclient-sdk-linux.x64-12.2.0.1.0.zip
[root@rhl6 opt]# ls
instantclient_12_2
然后解壓并編譯oci8-2.1.4.tgz乏德,注意編譯參數(shù)的目錄要跟你所解壓的Oracle instant Client Lib目錄對(duì)應(yīng)
[root@rhl6 opt]# tar zxvf oci8-2.1.4.tgz
[root@rhl6 opt]# cd oci8-2.1.4
[root@rhl6 opt]# phpize
[root@rhl6 opt]# ./configure -with-oci8=instantclient,/opt/instantclient_12_2
[root@rhl6 opt]# make && make install
安裝完成后在php.ini加入extension=oci8.so
并且重新加載php-fpm/etc/init.d/php-fpm reload
即可完成oci8拓展的配置撤奸。
(三)錯(cuò)誤
1.遇到libclntsh.so not found的錯(cuò)誤
給libclntsh.so.*.1做個(gè)軟連接libclntsh.so
[root@rhl6 opt]# cd /opt/instantclient_12_2
[root@rhl6 instantclient_12_2]# ln -s libclntsh.so.12.1 libclntsh.so
三、Demo
// demo.php
$username = 'user';
$password = 'user12345';
// oracle10格式:[//]host_name[:port][/service_name] 示例://192.168.128.28:1521/USERDEV
// oracle11格式:[//]host_name[:port][/service_name][:server_type][/instance_name] 示例://192.168.128.28:1521/USERDEV
$connectText = '//192.168.128.28:1521/USERDEV';
putenv("NLS_LANG=SIMPLIFIED CHINESE_CHINA.ZHS16GBK");
$conn = oci_connect($username, $password, $connectText);
if (!$conn) {
$e = oci_error();
echo 'Oracle連接失敗<br />';
exit($e['message']);
}
echo 'Oracle連接完成';
// Prepare the statement
$stid = oci_parse($conn, "SELECT * FROM MYDB.USER");
if (!$stid) {
$e = oci_error($conn);
exit($e['message']);
}
// Perform the logic of the query
$r = oci_execute($stid);
if (!$r) {
$e = oci_error($stid);
exit($e['message']);
}
// Fetch the results of the query
print "<table>\n";
while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) {
print "<tr>\n";
foreach ($row as $item) {
$item = ($item !== null ? mb_convert_encoding($item, 'utf-8', 'gbk') : " ");
print " <td>" . $item . "</td>\n";
}
print "</tr>\n";
}
print "</table>\n";
oci_free_statement($stid);
oci_close($conn);