PHP + Oracle 的成功經驗

大部分的情況使用者都是採用PHP + MySQL。 但難免需要PHP + Oracle的情況。可惜網路上的資訊都還需要好好的消化及仔細設定。

以下是個人”終於”成功的經驗。

 

1. 讓PHP server可以執行oci的指令。需要新增dll。

請下載 Oracle Express Edition (Oracle 載就有~)

下載安裝完後 去它的資料夾裡的bin資料夾找這三個dll:

oci.dll
ociw32.dll
oraocixe10.dll

把”C:\oraclexe\app\oracle\product\11.2.0\server\bin” 路徑添加到 “PATH” 中 (PATH在環境變數裡~)

2. 設定 PHP.ini

在PHP5的資料夾內找出PHP.ini

開啟PHP.ini 並將以下的註解刪掉

;extension=php_oci8.dll
;extension=php_oracl.dll

存檔後 重新啟動Apache

並開啟phpinfo 查看裡面是否有 oci8 的部分 (如果有表示成功~)

在來就是重新開機 (讓新設的”PATH”變數生效)

3. PHP連結Oracle的語法

$ora_db_host = “120.110.xxx.xxx”;  //IP or host name
$ora_db_port = “1521”;  //port number, default 1521
$ora_db_sid = “orcl”;  //sid, default orcl

$ora_db_user = “HR”; // user id
$ora_db_pswd = “xxxxxxx”; // password

$ora_db = “(DESCRIPTION = (ADDRESS = (PROTOCOL = TCP)(HOST = $ora_db_host)(PORT = $ora_db_port))(CONNECT_DATA = (SID = $ora_db_sid)))”;   //

$charset = “UTF8”;  //charset
//$charset = “AL32UTF8”;

$conn = oci_connect($ora_db_user, $ora_db_pswd, $ora_db, $charset);

//$conn = oci_connect(‘hr’, ‘welcome’, ‘localhost/XE’);

if (!$conn) { //判斷是否連結成功
$e = oci_error();
trigger_error(htmlentities($e[‘message’], ENT_QUOTES), E_USER_ERROR);
}
echo “Server Version: ” . oci_server_version($conn) .”<br />”;
$sql = “SELECT * FROM employees where rownum <=20”;  //SQL statement

// Prepare the statement
$stid = oci_parse($conn, $sql);
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
echo “<table border=’1′>\n”;

//列印表頭
$ncols = oci_num_fields($stid);
echo “<tr>”;
for ($i = 1; $i <= $ncols; $i++) {
$column_name = oci_field_name($stid, $i);
echo “<th>”. $column_name . “</th>”;
}
echo “</tr>\n”;
//列印列
while ($row = oci_fetch_row($stid)) {

echo”<tr>\n”;
for($i = 0; $i < $ncols; $i++) {
echo “<td>” . $row[$i] . “</td>\n”;
}
echo “</tr>\n”;
}
echo “</table>\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”;

oci_free_statement($stid);
oci_close($conn);

 

 

主要參考: http://a159874a.pixnet.net/blog/post/12647770-php-%E9%80%A3%E4%B8%8A-%E9%81%A0%E7%AB%AF-oracle-%E7%9A%84-%E6%AD%A5%E9%A9%9F-~-(%E7%8F%BE%E5%9C%A8%E6%98%AF%E5%87%8C%E6%99%A8%E4%B8%89%E9%BB%9E

This entry was posted in Programming and tagged , . Bookmark the permalink.

Leave a Reply

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