PHP连接Oracle数据库

一般大家不这么做。

不难,和连接MySQL差不多。php需要使用OCI8扩展来连接Oracle,可以使用phpinfo来查看你是否已经安装了该扩展。关于OCI8的详细使用可以直接参考php的Manual OCI8,本文仅做一个入门介绍。

1. 使用什么帐号连接
$ora_host = "172.19.*.259"; $ora_port="1521"; $ora_sid = "orasid"; $ora_username = "orauser"; $ora_password = "orapwd"; $charset = "UTF8"; ### zhs16gbk ###

2. 构建Easy Connect string

(如果tnsnames.ora中已经有了,可以直接使用Connect Name)

$ora_connstr = "(description=(address=(protocol=tcp) (host=".$ora_host.")(port=".$ora_port.")) (connect_data=(service_name=".ora_sid.")))";

关于具体的Connect String构造不同的Oracle版本略有不同,详细参考对应版本的Easy Connect Naming

3. 连接数据库

使用oci_connect函数就可以连接Oracle了(其实和连接MySQL大同小异)。

$conn = oci_connect($ora_username, $ora_password,$ora_connstr,$charset); if (!$conn) { $e = oci_error(); trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR); }
4. 执行Query
$stid = oci_parse($conn, 'SELECT * FROM employees'); oci_execute($stid);
5. 获取结果

在while循环中使用oci_fetch_array遍历结果。

echo "<table border='1'>\n"; while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) { echo "<tr>\n"; foreach ($row as $item) { echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n"; } echo "</tr>\n"; } echo "</table>\n";
6. 全部代码
$ora_host = "172.19.*.259"; $ora_port="1521"; $ora_sid = "orasid"; $ora_username = "orauser"; $ora_password = "orapwd"; $charset = "UTF8"; ### zhs16gbk ### $ora_connstr = "(description=(address=(protocol=tcp) (host=".$ora_host.")(port=".$ora_port.")) (connect_data=(service_name=".ora_sid.")))"; $conn = oci_connect($ora_username, $ora_password,$ora_connstr); if (!$conn) { $e = oci_error(); trigger_error(htmlentities($e['message'], ENT_QUOTES), E_USER_ERROR,$charset); } $stid = oci_parse($conn, 'SELECT * FROM employees'); oci_execute($stid); echo "<table border='1'>\n"; while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) { echo "<tr>\n"; foreach ($row as $item) { echo " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : "&nbsp;") . "</td>\n"; } echo "</tr>\n"; } echo "</table>\n";
参考文献:

1. Oracle OCI8

2. 参考了俊达的代码

5 responses to “PHP连接Oracle数据库”

Leave a Reply

Your email address will not be published. Required fields are marked *