PHP
downloads | documentation | faq | getting help | mailing lists | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

oci_define_by_name> <oci_commit
Last updated: Fri, 10 Oct 2008

view this page in

oci_connect

(PHP 5, PECL oci8:1.1-1.2.4)

oci_connectÉtablit une connexion avec un serveur Oracle

Description

resource oci_connect ( string $username , string $password [, string $db [, string $charset [, int $session_mode ]]] )

Retourne une ressource de connexion Oracle, nécessaire à la plupart des appels OCI.

Liste de paramètres

username

Le nom d'utilisateur Oracle.

password

Le mot de passe de l'utilisateur.

db

Ce paramètre optionnel contient le nom de l'instance locale d'Oracle, ou le nom de l'entrée dans le fichier tnsnames.ora auquel vous voulez vous connecter.

S'il n'est pas spécifié, PHP va utiliser la variable d'environnement ORACLE_SID (Oracle instance) ou TWO_TASK (tnsnames.ora) pour déterminer la base à laquelle se connecter.

charset

Si vous utilisez un serveur Oracle version 9.2 et suivant, vous pouvez renseigner le paramètre charset , qui peut être utilisé dans la nouvelle connexion. Si vous utilisez un serveur Oracle inférieur à la version 9.2, ce paramètre sera ignoré et la variable d'environnement NLS_LANG sera utilisée à la place.

session_mode

Ce paramètre est disponible depuis la version 1.1 et accepte les valeurs suivantes : OCI_DEFAULT, OCI_SYSOPER et OCI_SYSDBA. Si OCI_SYSOPER ou OCI_SYSDBA est spécifié oci_connect() tentera d'établir une connexion privilégiée en utilisant des droits externes. Les connexions privilégiées sont désactivées par défaut. Pour les activer, vous devez définir oci8.privileged_connect à On.

Valeurs de retour

Retourne un identifiant de connexion ou FALSE si une erreur survient.

Exemples

Exemple #1 Exemple avec oci_connect()

<?php
echo "<pre>";
$db "";

$c1 oci_connect("scott""tiger"$db);
$c2 oci_connect("scott""tiger"$db);

function 
create_table($conn)
{
  
$stmt oci_parse($conn"create table scott.hallo (test varchar2(64))");
  
oci_execute($stmt);
  echo 
$conn " created table\n\n";
}

function 
drop_table($conn)
{
  
$stmt oci_parse($conn"drop table scott.hallo");
  
oci_execute($stmt);
  echo 
$conn " dropped table\n\n";
}

function 
insert_data($conn)
{
  
$stmt oci_parse($conn"insert into scott.hallo
            values('$conn' || ' ' || to_char(sysdate,'DD-MON-YY HH24:MI:SS'))"
);
  
oci_execute($stmtOCI_DEFAULT);
  echo 
$conn " inserted hallo\n\n";
}

function 
delete_data($conn)
{
  
$stmt oci_parse($conn"delete from scott.hallo");
  
oci_execute($stmtOCI_DEFAULT);
  echo 
$conn " deleted hallo\n\n";
}

function 
commit($conn)
{
  
oci_commit($conn);
  echo 
$conn " committed\n\n";
}

function 
rollback($conn)
{
  
oci_rollback($conn);
  echo 
$conn " rollback\n\n";
}

function 
select_data($conn)
{
  
$stmt oci_parse($conn"select * from scott.hallo");
  
oci_execute($stmtOCI_DEFAULT);
  echo 
$conn."----selecting\n\n";
  while (
oci_fetch($stmt)) {
    echo 
$conn " [" oci_result($stmt"TEST") . "]\n\n";
  }
  echo 
$conn "----done\n\n";
}

create_table($c1);
insert_data($c1);   // Insertion d'une ligne via c1
insert_data($c2);   // Insertion d'une ligne via c2

select_data($c1);   // Résultat des insertions
select_data($c2);

rollback($c1);      // Annulation sur c1

select_data($c1);   // Les deux insertions ont été annulées
select_data($c2);

insert_data($c2);   // Insertion d'une ligne via c2
commit($c2);        // Validation via c2

select_data($c1);   // Le résultat de c2 est retourné

delete_data($c1);   // Effacement de toute la table via c1
select_data($c1);   // Aucune ligne de trouvée
select_data($c2);   // Aucune ligne de trouvée
commit($c1);        // Validation via c1

select_data($c1);   // Aucune ligne de trouvée
select_data($c2);   // Aucune ligne de trouvée

drop_table($c1);
echo 
"</pre>";
?>

Notes

Note: Si vous utilisez PHP avec le client Instant Oracle, vous pouvez utiliser la méthode de nommage facile de connexion tel que décrit ici : » http://download-west.oracle.com/docs/cd/B12037_01/network.101/b10775/naming.htm#i498306. En fait, cela signifie que vous pouvez spécifier "//db_host[:port]/database_name" en tant que nom de base de données. ais, si vous voulez utiliser l'ancienne méthode de nommage, vous devez définir soit ORACLE_HOME, soit TNS_ADMIN.

Note: Le second appel ainsi que les suivants à la fonction oci_connect() avec les mêmes paramètres retournera le gestionnaire de connexion retourné lors du premier appel. Cela signifie que les requêtes envoyées sur un gestionnaire seront également envoyées aux autres gestionnaires, car c'est le même gestionnaire. Ce comportement est démontré dans l'exemple 1 ci-dessous. Si vous avez besoin de deux gestionnaires, dont les transactions sont isolées, vous devez utiliser la fonction oci_new_connect() à la place.

Note: Dans les versions de PHP antérieures à la version 5.0.0, vous devez utiliser la fonction ocilogon(). Cet ancien nom est toujours utilisable : un alias a été fait vers la fonction oci_connect(), pour assurer la compatibilité ascendante. Toutefois, il est recommandé de ne plus l'utiliser.



oci_define_by_name> <oci_commit
Last updated: Fri, 10 Oct 2008
 
add a note add a note User Contributed Notes
oci_connect
sixd at php dot net
21-Jul-2008 01:16
From PHP 5.3 onwards:

A new OCI_CRED_EXT flag can be passed as the "session_mode" parameter
to oci_connect(), oci_new_connect() and oci_pconnect().

  $c1 = oci_connect("/", "", $db, null, OCI_CRED_EXT);

This tells Oracle to do external or OS authentication, if configured
in the database.

OCI_CRED_EXT can only be used with username of "/" and a empty
password.  Oci8.privileged_connection may be On or Off. 

OCI_CRED_EXT is not supported on Windows for security reasons.

The new flag may be combined with the existing OCI_SYSOPER or
OCI_SYSDBA modes (note: oci8.privileged_connection needs to be On for
OCI_SYSDBA and OCI_SYSOPER), e.g.:

  $c1 = oci_connect("/", "", $db, null, OCI_CRED_EXT+OCI_SYSOPER);
sixd at php dot net
30-Jun-2008 04:33
If you want to specify a connection timeout in case there is network problem, you can edit the client side (e.g. PHP side) sqlnet.ora file and set SQLNET.OUTBOUND_CONNECT_TIMEOUT. This sets the upper time limit for establishing a connection right through to the DB, including the time for attempts to connect to other services.   It is available from Oracle 10.2.0.3 onwards.

In Oracle 11.1, a slightly lighter-weight solution TCP.CONNECT_TIMEOUT was introduced.  It also is a sqlnet.ora parameter.  It bounds just the TCP connection establishment time, which is mostly where connection problem are seen.

The client sqlnet.ora file should be put in the same directory as the tnsnames.ora file.
sxid at php dot net
20-Jun-2008 03:46
If PHP is built with Oracle 9.2 or greater client libraries, the
charset parameter is used to determine the character set used by the
Oracle client libraries.  When PHP is built with older Oracle client
libraries, or if the parameter is not passed, Oracle NLS environment
variables such as NLS_LANG will be used to determine the character
set.

The character set does not need to match that used by the database.
If it doesn't, Oracle will do its best to convert data to and from the
database character set.  Depending on the character sets, this may not
which may always be give usable or valid results, and it can reduce
overall performance

Because passing the parameter removes the environment look up, it can
improve connection performance
sebastien.barbieri _at_ gmail dot com
13-Sep-2006 09:42
When you are using Oracle 9.2+ I would say that you MUST use the CHARSET parameter.

Of course, you will not notice it until there is accented character... so just specify it and you will avoid a big headache.

So for example here is our Oracle internal conf:
select * from nls_database_parameters;
 
PARAMETER                      VALUE
------------------------------ ----------------------------------------

NLS_LANGUAGE                   AMERICAN
NLS_TERRITORY                  AMERICA
NLS_ISO_CURRENCY               AMERICA
NLS_CHARACTERSET               WE8ISO8859P15

 
And there our oci_connect call:

$dbch=ocilogon($user,$pass,$connectString,"WE8ISO8859P15");

Without that, you will get question mark (inversed), squares… instead of most accented character.

Don’t forget to use that for writing as well as for reading.
greatval <wow> gmail <dot> com
24-Jul-2006 09:30
For use PHPv5 functions in PHPv4 i use simple script:
<?php
$funcs
=array(
       
'oci_connect'=>'OCILogon',
       
'oci_parse'=>'OCIParse',
       
'oci_execute'=>'OCIExecute',
       
'oci_fetch'=>'OCIFetch',
       
'oci_num_fields'=>'OCINumCols',
       
'oci_field_name'=>'OCIColumnName',
       
'oci_result'=>'OCIResult',
       
'oci_free_statement'=>'OCIFreeStatement',
);
// yoy can add yours pairs of funcs.

foreach ($funcs as $k=>$v)
    {
        if (!
function_exists($k))
            {
               
$arg_string='$p0';
                for (
$i=1;$i<20;$i++) {
                   
$arg_string.=',$p'.$i;
                }
                eval (
'function '.$k.' () {
                        list('
.$arg_string.')=func_get_args();
                        return '
.$v.'('.$arg_string.');
                        }
                '
);
            }
    }
?>

simple, but it work. :-)
Andrei
07-Nov-2005 05:08
lost oracle connection. need restart apache?

Temporarely you can prevent 'connection lost' by using folowing script (use it at your own risk):

<?php
$rnum
=rand(0,99999999);
$dbcon = oci_new_connect('XXXXX', 'XXXXXX',
'
(DESCRIPTION =
           (ADDRESS =
        (PROTOCOL = TCP)
        (HOST = XXX.XXX.XXX.XXX)
        (PORT = 1521)
        (HASH = '
.$rnum.')
     )
         (CONNECT_DATA =(SID = XXX))
     )
'
);
?>
Domenico a01b20_NOSPAM_ at iol dot it
07-Nov-2005 12:44
This note is an addendum to note#58378
Seems to be a good workaround set the oracle_home and/instead of the tns_admin.
tnsnames.ora must to be located in
$ORACLE_HOME/network/admin
and in
$TNS_ADMIN/ (if you use it)

---
Best Regards,
Domenico
a01b02_NO_SPAM at iol dot it
02-Nov-2005 02:44
Using tnsnames.ora
Apache 2
php 5.0.5
Oracle 10 IstantClient

PHP half of times return this error:

OCISessionBegin: ORA-24327: need explicit attach before authenticating a user in ...

In Oracle manual I find:

ORA-24327 need explicit attach before authenticating a user

    Cause: A server context must be initialized before creating a session.
    Action: Create and initialize a server handle.

I resolved using Easy Connect Naming Method.

Notice of this problem in bug#29779.

---
Best Regards,
Domenico
Chris
27-Oct-2005 05:19
Our tnsnames.ora uses the SERVICE_NAME=mydb - which for some reason wont work with PHP even though it works fine with tnsping. Using SID=mydb worked and a connection was established.

oci_define_by_name> <oci_commit
Last updated: Fri, 10 Oct 2008
 
 
show source | credits | stats | sitemap | contact | advertising | mirror sites