PHP: Oracle 関数 - Manual
PHP  
downloads | documentation | faq | getting help | mailing lists | | php.net sites | links | my php.net 
search for in the  
<openssl_x509_readOra_Bind>
view the version of this page
Last updated: Tue, 21 Dec 2004

LXXXIII. Oracle 関数

導入

この拡張モジュールによりOracleデータベースサーバへのアクセスが可 能となります。OCI8拡張モジュール も参照して下さい。

インストール手順

オプション--with-oracle[=DIR]を指 定してPHPをコンパイルする必要があります。ただし、DIRのデフォルトは、 環境変数ORACLE_HOMEの値です。

定義済みの定数

これらの定数は、この拡張モジュールで定義されており、 この拡張モジュールがPHP内部にコンパイルされているか実行時に動的にロー ドされるかのどちらかの場合のみ使用可能です。

ORA_BIND_INOUT (integer)

ORA_BIND_IN (integer)

ORA_BIND_OUT (integer)

ORA_FETCHINTO_ASSOC (integer)

ORA_FETCHINTO_NULLS (integer)

目次
Ora_Bind --  PHP変数をOracleパラメータにバインドする
Ora_Close -- Oracleカーソルをクローズする
Ora_ColumnName -- Oracle結果カラムの名前を取得する
Ora_ColumnSize -- Oracle 結果カラムのサイズを得る
Ora_ColumnType -- Oracleのカラムの型を取得する
Ora_Commit -- Oracleトランザクションをコミットする
Ora_CommitOff -- オートコミットをオフにする
Ora_CommitOn -- オートコミットを有効にする
Ora_Do -- パース、実行、取得
Ora_Error -- Oracleエラーメッセージの取得
Ora_ErrorCode -- Oracleエラーコードの取得
Ora_Exec --  Oracleカーソル上でのパースしたステートメントの実行
Ora_Fetch_Into -- 指定した配列resultにレコードを取得する
Ora_Fetch -- カーソルから1行分のデータを取得
Ora_GetColumn -- 取得した行からデータを得る
Ora_Logoff -- Oracle接続を閉じる
Ora_Logon -- Oracle接続をオープンする
Ora_Numcols -- カラム数を返す
Ora_Numrows -- レコード数を返す
Ora_Open -- Oracleカーソルをオープンする
Ora_Parse -- SQLステートメントを解釈する
Ora_pLogon --  持続的な Oracle接続をオープンする
Ora_Rollback -- トランザクションをロールバックする


add a note add a note User Contributed Notes
Oracle 関数
gewj at skyone dot com dot cn
09-Nov-2004 03:23
I got a simple way to let php5 work with oracle 9i seamlessly.
   According to the normal case,it reports a error not to find libclntsh while compiling the php5.You could do a soft link as follow:
  ln -s $ORACLE_HOME/lib/libclntsh.so.9.0 $ORACLE_HOME/lib/libclntsh.so

   After that, you recompile the php5 and it'sl ok now.
spam2004 at turniton dot dk
17-Aug-2004 01:32
I had a hard time getting Oracle to work with the new PHP5 - here is a short step by step guide that may be usefull to others..

Oracle installation problems and workarounds for Fedora2 and Debian..

1) Get the oracle client stuff and put it into /usr/lib/oracle..
My output from "ls -R /usr/lib/oracle/"
/usr/lib/oracle/:
10.1.0.2
/usr/lib/oracle/10.1.0.2:
client
/usr/lib/oracle/10.1.0.2/client:
lib
/usr/lib/oracle/10.1.0.2/client/lib:
classes12.jar  libclntsh.so  libclntsh.so.10.1  libnnz10.so  libocci.so.10.1  libociei.so  libocijdbc10.so  ojdbc14.jar

2) Set the ORACLE environment vars
export ORACLE_HOME=/usr/lib/oracle/10.1.0.2/client/
export LD_LIBRARY_PATH=/usr/lib/oracle/10.1.0.2/client/lib
export NLS_LANG=DANISH

3) Get the oracle source files
nzerror.h  oci1.h    ociap.h  ocidef.h  ocidfn.h  oci.h    ocikpr.h    ori.h  oro.h nzt.h oci8dp.h  ociapr.h  ocidem.h  ociextp.h  ocikp.h  oratypes.h  orl.h  ort.h

4) edit the file oci.h and add a line in the top below the comments
#define OCI_NLS_CHARSET_ID 0

5) Copy the oracle source files (.h and .c) files to
php-5.0.0/ext/oci8/ and also copy them to php-5.0.0/main/

6) Goto the php-5.0.0. dir and do a ./configure --with-oci8 and other stuff you need..

7) make install

8) Add these lines to /etc/rc.d/initd/httpd

export LD_LIBRARY_PATH=/usr/lib/oracle/10.1.0.2/client/lib
export NLS_LANG=DANISH
export ORACLE_HOME=/usr/lib/oracle/10.1.0.2/client/lib
export LD_LIBRARY_PATH=/usr/lib/oracle/10.1.0.2/client/lib
export TZ=GMT
export NLS_DUAL_CURRENCY='.'

# Notice the line export NLS_DUAL_CURRENCY='.' is needed to get the stuff to run correctly on Fedora 2 .. otherwise you get a nasty misleading error about invalid username or password!.
zyablik at insc dot ru
07-Apr-2004 05:56
Oracle Client 9i on Windows XP (2000) plus IIS, plus Oracle RDBMS on remote server.
The bad thing that nothing will be working on windows-based comp. until you will not change the proper permissions on some files.

Fist you will need to set environment
ORACLE_SID (not necessary)
ORACLE_HOME (necessary)
TNS_ADMIN (necessary).

Second: add user IUSR_user read permission on the directory pointed by TNS_ADMIN. The same user permission r/x on the file orannts9.dll in ORACLE_HOME\bin (this was finded experimentally). After this instructions  ora_logon or ocilogon will be executed without deadly error codes ORA-12154 or ORA-12538.
nasser / at / unixica dot com
18-Mar-2004 08:52
More on the header files needed to compile PHP...

I installed the client side of Oracle 9i for Linux in different configurations, and could not get the oci*.h files that PHP requires for compilation.  So in the end, I searched for them through the jar files, and here's the result:

As you probably know, the Oracle for Linux package comes in three download files, or three disks.  Go to this path:

/path/to/disks/Disk2/stage/Components/oracle.rdbms.oci

The rest of the directories are based on the release number, so they may look a little bit different but you get the picture:

9.2.0.1.0/1/DataFiles/public.1.1.jar

and use "jar xf" to extract it and grab the header files.  Copy them to:

$ORACLE_HOME/rdbms/demo

And your make will work.  Since this wasted half of a day of mine (even after going through lots of comments on the Internet) I hope it saves somebody else's time...

Nasser
php kosmisk dk (punctuation needed)
12-Jan-2004 06:21
To make sure my oracle get's rolledback when my script once in a while dies or I make a mistake (statements are terminated with ";"...). I use this construction. Because if it isn't rolled back and you use plogon, other oracle connections might hang, until the apache process that ran the failed script is terminated, and therefore releases the connection and gives the implicit rollback.

The use of a shutdown_function:

$oracle = ora_plogon("user/pass@db", "") or die("Can't connect to db");
$cursor = ora_open($oracle);
ora_commitoff($oracle);

function ora_shutdown() {
  global $oracle;
  global $cursor;
  ora_rollback($oracle);
  ora_close($cursor);
  ora_logoff($oracle);
}

register_shutdown_function(ora_shutdown);
http://iubito.free.fr
30-Dec-2003 01:04
Here is my little but very very useful tutorial :-)

CONNECTION : (in connect.php)
<?php
$ora_conn
= ora_logon("databaseName@service","pass");
?>
-----------------------------
DISCONNECT : (in disconnect.php)
<?php
ora_logoff
($ora_conn);
?>
-----------------------------
In each page, you must include both files
<?php
include("connect.php");
blah blah
include("disconnect.php");
?>
-----------------------------

Now the hard... SELECT ! (in select.php)
<?php
// Comment the line error_reporting if you want to
// debug your code - for example the "NO DATA FOUND"
// when no result. Oracle returns this like an error.
error_reporting(0);

// Create an array, a cursor, count number of cols,
// perform the fetch and insert in the array.
$results = array();
$ora_cur = ora_do($ora_conn, $query);
// Don't panic, the $query will be set, wait a bit :)

if ($ora_cur)
{
 
// Number of cols
 
$numCols = ora_numcols($ora_cur);

 
// Put the first line in the array...
 
$row = array();
  for(
$i=0; $i<$numCols; $i++)
  {
// for each column
  
$row[ora_columnname($ora_cur,$i)] = ora_getcolumn($ora_cur,$i);
  }
 
array_push($results,$row);

 
// "Fetch" all records, one by one, and create an array for each one.
  // Each array is "pushed" in the $results array.
 
while (ora_fetch($ora_cur))
  {
// for each record
  
$row = array();
   for(
$i=0; $i<$numCols; $i++)
   {
// for each column
    
$row[ora_columnname($ora_cur,$i)] = ora_getcolumn($ora_cur,$i);
   }
  
// Push $results
  
array_push($results,$row);
  }
}
// Now turns error_reporting on. Comment this line if you want
// to see "NO DATA FOUND" warnings.
error_reporting(1);
?>
--------------------------

And now let's enjoy with this simple page !! :)

<?
include("connect.php");
echo
"blah blah";
$query = "select NAME, AGE from people where...";

include(
"select.php");

// Browse $results array and display results :
if (count($results)) // if no "NO DATA FOUND"
{
 
reset($results);
 while(
$res=each($results))
 {
/*
 $res is like :
array(0 => array('NAME' => 'Sylvain', 'AGE' => '21'),
     1 => array('NAME' => 'Somebody','AGE' => '888'));
 */
 
echo $res[1]['NAME']; // name
 
echo $res[1]['AGE']; // age
  // ALLWAYS write in uppercase !
 
}
}
else
// NO_DATA_FOUND :(
{
 echo
"There's nobody in your database :D";
}

echo
"blah blah and again blah";
//...another queries
$query = "...";
include(
"select.php");...

include(
"disconnect.php");
?>

----------------------
Another queries (insert, update...) are simpler. Let's see :)
<?php
include("connect.php");
$query = "UPDATE people SET url=' where name='Sylvain'";
include(
"query.php");
include(
"disconnect.php");
?>

and query.php is :
<?php
$cursor
= ora_open($ora_conn); // Create a cursor
if($cursor) // if created
{
 
// Parse query
 
$resultat = ora_parse($cursor,$query);
 
$resultat = ora_exec($cursor); // Execute
 
$a=ora_commit($ora_conn); // perform COMMIT
 
$b=ora_close($cursor); // close cursor
}
else
{
// Write an error message
 
echo "oh, oh ! problem...";
}
?>

Now enjoy using it !
For more information, see my website in French
hsin at med dot cgu dot edu dot tw
10-Nov-2003 03:02
I got error messages when compiling after configured php-4.3.4, apache-1.3.29 and with Oracle client 9.2.0 (MySQL also) installed.

My configure command was:

./configure \
--with-mysql \
--with-oracle=$ORACLE_HOME \
--with-oci8=$ORACLE_HOME \
--enable-sigchild \
--enable-track-vars \
--with-xml \
--with-apache=../apache_1.3.29 \
--enable-exif

What made the error was lack of some headers (ociextp.h, oci.h...etc) These headers are located in the following dirs:

$ORACLE_HOME/rdbms/public
$ORACLE_HOME/rdbms/demo

Just install the Oracle developement kit in the Oracle database folder, I suggest using custum selection if passing php compilation is all yo want:)

One can either make sure these two directories are included or just copy the *.h into php-4.3.4/include
helvecio_oliveira at yahoo dot com dot br
13-Oct-2003 07:45
Some good links from OTN:

Installing Oracle, PHP, and Apache on Linux:
otn.oracle.com/tech/opensource/php/apache/inst_php_apache_linux.html

Forums Home->OTN->Technologies->PHP:
forums.oracle.com/forums/forum.jsp?forum=178

Forums Home->OTN->Technologies->Linux:
forums.oracle.com/forums/forum.jsp?forum=135
john at no_gay_refereces_please dot com
23-Apr-2003 08:03
Ok. Considering it took me about three hours to find the answer to this:

Running a stored procedure in Oracle 8i + PHP4 (explicitly).

$sql = "begin procedure_name($required_variables_string); end;";

... execute code here...

but your string should look like what is given above.
For example, if I was going to execute the following:
$sql = "SELECT * from some_table"; looks like straight SQL, vs the one above which looks more like a PL/SQL block.

A bit gay in my opinion, but this is my 2c for those who might need to know how to execute a stored procedure using PHP.
thebestion at gmx dot de
09-Oct-2002 04:48
A simple function

# list query in array
#
# $conn: connection
# $query: query_string
#
# return: $templist[$row][$column]=$value;

function get_query($conn,$query){
 $cursor = ora_open($conn);
 ora_parse($cursor, $query) or die;
 ora_exec($cursor);
 $numcols = ora_numcols($cursor);
 $i=0;
 while(ora_fetch($cursor)){
  for($column=0; $column < $numcols; $column++){
   $colname = trim(ora_columnname($cursor, $column));
   $data = trim(ora_getcolumn($cursor, $column));

   $templist[$i][$colname]=$data;
  }
  $i++;
 }
 return $templist;
}

i.e.:

$conn = ora_plogon( "user", "passwd")or die;

$cursor = ora_open($conn);

ora_commitoff($conn);

$query = "SELECT * FROM table";

$result=get_query($conn,$query);

for($i=0;$result[$i];$i++){
 echo $result[$i][column];
}
jjuffermans at chello dot com
16-Mar-2001 11:11
The following function returns more detailed information about the columns of a table. It returns an array of hashes, with columnname, type, size, precision, scale, nullable, comments and constraints.

   function columninfo($cursor, $table) {
       $query  = "SELECT";
       $query .= "  user_tab_columns.column_name,";
       $query .= "  user_tab_columns.data_type,";
       $query .= "  user_tab_columns.data_length,";
       $query .= "  user_tab_columns.data_precision,";
       $query .= "  user_tab_columns.data_scale,";
       $query .= "  user_tab_columns.nullable,";
       $query .= "  user_col_comments.comments,";
       $query .= "  (SELECT";
       $query .= "    constraint_name";
       $query .= "    FROM user_cons_columns";
       $query .= "    WHERE column_name = user_tab_columns.column_name)";
       $query .= " FROM user_tab_columns,";
       $query .= " user_col_comments";
       $query .= " WHERE user_tab_columns.table_name = '$table'";
       $query .= " AND user_tab_columns.column_name = user_col_comments.column_name";
       $query .= " ORDER BY user_tab_columns.column_id ASC NULLS FIRST";
       ora_parse($cursor, $query) or die("<hr /><h2 style=\"color:#ff0000\">" . ora_error($cursor) . "</h2><tt>$query</tt>");
       ora_exec($cursor) or die("<hr /><h2 style=\"color:#ff0000\">" . ora_error($cursor) . "</h2><tt>$query</tt>");
       $ret_array = array();
       while (ora_fetch($cursor)) {
           $column_name = strtolower(ora_getcolumn($cursor, 0));
           $data_type = ora_getcolumn($cursor, 1);
           $data_length = ora_getcolumn($cursor, 2);
           $data_precision = ora_getcolumn($cursor, 3);
           $data_scale = ora_getcolumn($cursor, 4);
           $nullable = ora_getcolumn($cursor, 5);
           $nullable = ($nullable == "Y");
           $comments = ora_getcolumn($cursor, 6);
           $constraint_name = strtolower(ora_getcolumn($cursor, 7));
           if ($data_precision) {
               $data_length = $data_precision + (($data_scale) ? 1 : 0);
           }
                       $ret_array[] = array(
               "column_name"        => $column_name,
               "data_type"            => $data_type,
               "data_length"        => $data_length,
               "data_precision"    => $data_precision,
               "data_scale"        => $data_scale,
               "nullable"            => $nullable,
               "comments"            => $comments,
               "constraint_name"    => $constraint_name
           );
       }
       return $ret_array;
   }
jjuffermans at chello dot com
15-Mar-2001 06:10
Usefull system table: all_tab_comments

It shows all tables/views that you can read, including a lot of other usefull system tables like user_objects, user_tab_columns, user_constraints.
aedunov at cv dot jinr dot ru
14-Jan-2001 02:09
If you use Oracle and PHP on the same computer, you can start only "dbstart" for runing PHP with Oracle and don't start "lsnrctl" maybe for security reason.
dmearls at yahoo dot com
05-Jan-2001 02:15
Here is a code sample that I used on NT 4.0 running Apache/Oracle 8.1.6/PHP 4.0 : I used it to connect to the sample scott-tiger schema EMP table. It is pretty much a hack, but I hope it helps you.

<?php

putenv
('ORACLE_SID=DMEARLS.WORLD');
putenv('ORACLE_HOME=d:\oracle\ora81');
putenv('TNS_ADMIN=d:\oracle\ora81\network\admin');
$foo=exec("echo %ORACLE_SID%");
echo
$foo;
//Set("ORACLE_SID=DMEARLS.WORLD");
//Set("ORACLE_HOME=D:\oracle\isuites");
       //$db = "dmearls.world";
       // create connection
   //  $connection = ora_logon("scott","tiger")
    
$connection = OCILogon("scott","tiger","dmearls.world")
               or die(
"Couldn't logon to database.");

      
// create SQL statement
      
$sql = "SELECT ENAME, SAL
               FROM EMP
               ORDER BY SAL"
;
echo
"<br>";
echo
$connection;
echo
"<br>";
echo
$sql;
echo
"<br>";

      
// parse SQL statement
      
$sql_statement = OCIParse($connection,$sql)
               or die(
"Couldn't parse statement.");
echo
$sql_statement;
      
// execute SQL query
      
OCIExecute($sql_statement)
               or die(
"Couldn't execute statement.");

      
// get number of columns for use later
      
$num_columns = OCINumCols($sql_statement);
echo
"<br>";
echo
$num_columns;
      
// start results formatting
      
echo "<TABLE BORDER=1>";
       echo
"<TR>
             <TH>Name</TH>
             <TH>Salary</TH>
             </TR>
             "
;

      
// format results by row
      
while (OCIFetch($sql_statement)) {
               echo
"<TR>";
               for (
$i = 1; $i < $num_columns; $i++) {

                      
$column_value1 = OCIResult($sql_statement,$i);
                      
$column_value2 = OCIResult($sql_statement,$i+1);
                      
//echo $i;
                              
echo "<TD>$column_value1</TD>";
                               echo
"<TD>$column_value2</TD>";
               }
               echo
"</TR>";
       }

       echo
"</TABLE>";

      
// free resources and close connection
      
OCIFreeStatement($sql_statement);
      
OCILogoff($connection);

      
?>
rs at aelea dot com
18-Aug-2000 09:28
Connecting to remote oracle database -

Is the same as a local database, but the remote database must be configured in your tnsnames.ora - its then provided to PHP by way of tns...
elf at messer dot de
27-Jul-2000 04:05
I contribute the following code example.

function GetNameFromUserId ($ID, &$User, &$Msg)
 {
  print('<BR>GetNameFromUserId Start');

  if ($Session = ora_plogon('Hello', 'World'))
   {
   print('<P>Session: ' . $Session . '<P>');

   if ($Cursor = ora_open($Session))
     {
     print('<P>Cursor: ' . $Cursor . '<P>');

     $SQL = 'SELECT NAME FROM PERSONS WHERE USERID = \''
             . $ID . '\'';
     print('<P>SQL: ' . $SQL . '<P>');

     // Prepare SQL statement
     if (ora_parse($Cursor, $SQL))
       {
       if (ora_exec($Cursor))
         {
         $Row[] = '';

         // Retrieve a complete row from the result set
         if (ora_fetch_into($Cursor, &$Row))
           {
           $User = 'count = ' . count($Row) . ': ';

           while (list($Key, $Value) = each($Row))
             {
             $User .= '<BR>Row[' . $Key . '] = ' . $Value;
             }

           $Result = 0;
           }
         else
           {
           $Msg = ora_error($Cursor);
           $Result = ora_errorcode($Cursor);
           }  // end of if expression
         }
       else
         {
         $Msg = ora_error($Cursor);
         $Result = ora_errorcode($Cursor);
         }  // end of if expression
       }
     else
       {
       $Msg = ora_error($Cursor);
       $Result = ora_errorcode($Cursor);
       }  // end of if expression

     ora_close($Cursor);
     }
   else
     {
     $Msg = ora_error($Session);
     $Result = ora_errorcode($Session);
     }  // end of if expression

   ora_logoff($Session);
   }
  else
   {
   $Msg = ora_error($Session);
   $Result = ora_errorcode($Session);
   }  // end of if expression

  print('<BR>GetNameFromUserId End');
  return $Result;
 }
lmg at webfarm dot com
03-Jan-2000 02:16
...and with the dawning of the new year, my TNS problem is gone. I've been having trouble connecting to a remote db server from Linux running Apache/PHP+Oracle. I'd set the ORACLE_HOME and ORACLE_SID (although, I'm not sure if it cares about the SID when connecting via SQL*Net/Net8) with no luck. The environment variable that does the trick is TNS_ADMIN. (I saw a mention of this on phpbuilder and thought I'd mention it here)<br>
Set TNS_ADMIN to the directory with your tnsnames.ora file and see if that dosen't help the TNS unable to connect problems<p>

setenv("TNS_ADMIN=/opt/oracle/product/8.1.5/network/admin");

... does the trick for me.
denkwerk-hamburg at denkwerk dot com
29-Jun-1999 06:33
ora_numrows($cursor) only works when there's  an ora_fetch before. it will return the number of rows resulting from the query.
denkwerk-hamburg at denkwerk dot com
29-Jun-1999 06:28
If you ever come accross trying to store non ASCII characters over PHP, ORACLE will probably not store thos characters properly, allthough you've set NLS_LANG and ORA_NLS33 in the Oracle User's ENV. the trick is to set these environment at Apaches' Startup. putenv and getenv didn't help at all. ) i meant apache's init script of course, provided you've got a SYS V style UNIX.
cord at ragesoft dot com
12-Feb-1999 09:21
Using "@dbname" in ora_logon/ora_plogon will force a SQL*Net connect, even if the database is on the local host.  It's more efficient to use the ORACLE_SID environment variable.

putenv( "ORACLE_SID=dbname" );
$handle = ora_plogon( "SCOTT",  "TIGER");
kk at shonline dot de
05-Aug-1998 03:09
Oracle Example
Prerequisites:

 You need to know the values of the following environment variables:

ORACLE_HOME
This is the path to your Oracle installation directory. It is usually defined in the UNIX login script of your oracle user and all Oracle client users.

ORACLE_SID
This is the name of the database instance you want to connect to. It is also defined in the UNIX environment of your oracle user and all Oracle client users.

Find out the values of these variables by loggin in as a user who can connect to the database in question with sqlplus. Then type at your Unix shell prompt:

prompt> echo $ORACLE_HOME
/opt/oracle/oracle/8.0.3
prompt> echo $ORACLE_SID
ORACLE

A simple PHP script using ora_* functions

<?php
  putenv
("ORACLE_SID=ORACLE");
 
putenv("ORACLE_HOME=/opt/oracle/oracle/8.0.3");

 
$conn = ora_login("scott", "tiger");
 
$curs = ora_open($conn);

 
ora_commitoff($conn);

 
$query = sprintf("select * from cat");

/* Long version */
/*
  ora_parse($curs, $query);
  ora_exec($curs);
  ora_fetch($curs);
*/
/* Short Version */
 
ora_do($conn, $query);

 
$ncols = ora_numcols($curs);
 
$nrows = ora_numrows($curs);
 
printf("Result size is $ncols cols by $nrows rows.<br>");

  for (
$i=0; $i<$ncols; $i++) {
  
printf("col[%s] = %s type[%d] = %s<br>",
    
$i, ora_columnname($curs, $i),
    
$i, ora_columntype($curs, $i));
  }

  for (
$j=0; $j<$nrows; $j++) {
   for (
$i=0; $i<$ncols; $i++) {
    
$col = ora_getcolumn($curs, $i);
    
printf(&quotval[%d, %d] = %s * ", $j, $i, ora_getcolumn($curs, $i);
   }
   printf("
<br>");
  }
 ?>

<openssl_x509_readOra_Bind>
 Last updated: Tue, 21 Dec 2004
show source | credits | sitemap | contact | advertising | mirror sites 
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: /
Last updated: Mon Mar 14 08:13:06 2005 Local time zone must be set--see zic manual page