views:

115

answers:

1

I'm using PHP and OCI8 to execute anonymous Oracle PL/SQL blocks of code. Is there any way for me to bind a variable and get its output upon completion of the block, just as I can when I call stored procedures in a similar way?

$SQL = "declare
something varchar2 := 'I want this returned';
begin
  --How can I return the value of 'something' into a bound PHP variable?
end;";
+2  A: 

You define an out parameter by using the keyword OUT between the name and data type declaration. IE:

CREATE OR REPLACE PROCEDURE blah (OUT_PARAM_EXAMPLE OUT VARCHAR2) IS ...

If not specified, IN is the default. If you want to use a parameter as both in and out, use:

CREATE OR REPLACE PROCEDURE blah (INOUT_PARAM_EXAMPLE IN OUT VARCHAR2) IS ...

The following example creates a procedure with IN and OUT parameters. The procedure is then executed and the results printed out.

<?php
   // Connect to database...
   $c = oci_connect("hr", "hr_password", "localhost/XE");
   if (!$c) {
      echo "Unable to connect: " . var_dump( oci_error() );
      die();
   }

   // Create database procedure...
   $s = oci_parse($c, "create procedure proc1(p1 IN number, p2 OUT number) as " .
                     "begin" .
                     "  p2 := p1 + 10;" .
                     "end;");
   oci_execute($s, OCI_DEFAULT);

   // Call database procedure...
   $in_var = 10;
   $s = oci_parse($c, "begin proc1(:bind1, :bind2); end;");
   oci_bind_by_name($s, ":bind1", $in_var);
   oci_bind_by_name($s, ":bind2", $out_var, 32); // 32 is the return length
   oci_execute($s, OCI_DEFAULT);
   echo "Procedure returned value: " . $out_var;

   // Logoff from Oracle...
   oci_free_statement($s);
   oci_close($c);
 ?>

Reference:

OMG Ponies
Does the stored procedure get created permanently or just for this session? I've used this method to receive OUT parameters from procedures I compiled in the database (it looks like this is doing the same thing, except creating the procedure first). I'd like to avoid creating any permanent objects in the database when I execute this code.
RenderIn
@Renderlin: Yes, the example from orafaq.com would create the stored procedure. You'd need to put the stored procedure in the DECLARE block of an anonymous PLSQL block, and make the `proc1(...` within the BEGIN/END portion in order to not create the procedure.
OMG Ponies
Much thanks... made my day.
RenderIn