These examples connect as the HR user, which is
the sample "Human Resources" schema supplied with the
Oracle database. The account may need to be unlocked and the
password reset before you can use it.
The examples connect to the XE database on your
machine. Change the connect string to your database before running
the examples.
Example #1 Basic query
This shows querying and displaying results. Statements in OCI8 use
a prepare-execute-fetch sequence of steps.
// Prepare the statement $stid = oci_parse($conn, 'SELECT * FROM departments'); 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 print "<table border='1'>\n"; while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS)) { print "<tr>\n"; foreach ($row as $item) { print " <td>" . ($item !== null ? htmlentities($item, ENT_QUOTES) : " ") . "</td>\n"; } print "</tr>\n"; } print "</table>\n";
oci_free_statement($stid); oci_close($conn);
?>
Example #2 Inserting with bind variables
Bind variables improve performance by allowing reuse of execution
contexts and caches. Bind variables improve security by preventing
some kinds of SQL Injection problems.
<?php
// Before running, create the table: // CREATE TABLE MYTABLE (mid NUMBER, myd VARCHAR2(20));
print '<table border="1">'; while ($row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_LOBS)) { print '<tr><td>'.$row['MYCLOB'].'</td></tr>'; // In a loop, freeing the large variable before the 2nd fetch reduces PHP's peak memory usage unset($row); } print '</table>';
?>
Example #5 Using a PL/SQL stored function
You must bind a variable for the return value and optionally for
any PL/SQL function arguments.
<?php
/* Before running the PHP program, create a stored function in SQL*Plus or SQL Developer:
CREATE OR REPLACE FUNCTION myfunc(p IN NUMBER) RETURN NUMBER AS BEGIN RETURN p * 3; END;
Example #7 Calling a PL/SQL function that returns a REF CURSOR
Each returned value from the query is a REF
CURSOR that can be fetched from.
<?php /* Create the PL/SQL stored function as:
CREATE OR REPLACE FUNCTION myfunc(p1 IN NUMBER) RETURN SYS_REFCURSOR AS rc SYS_REFCURSOR; BEGIN OPEN rc FOR SELECT city FROM locations WHERE ROWNUM < p1; RETURN rc; END; */