oci_bind_by_name

(PHP 5, PECL oci8:1.1-1.2.4)

oci_bind_by_name — Привязывает переменную PHP к соответствующей метке в SQL-выражении.

Описание

bool oci_bind_by_name ( resource $stmt , string $ph_name , mixed $&variable [, int $maxlength [, int $type ]] )

oci_bind_by_name() привязывает переменную variable к метке ph_name . Будет ли она использоваться для вывода или ввода - выяснится в процессе выполнения и необходимые ресурсы будут выделены по необходимости. Параметр length устанавливает максимальный объем в байтах получаемой переменной. Если параметр length равен -1, то oci_bind_by_name() будет использовать текущую длину variable как максимальную.

Если вы хотите привязать абстрактный тип данных (LOB/ROWID/BFILE), то вам необходимо сначала создать дескриптор с помощью oci_new_descriptor(). Параметр length не используется с абстрактными типами данных и должен быть равен -1. Параметр type говорит Oracle, какой тип дескриптора мы хотим использовать. Возможные значения этого параметра:

  • OCI_B_FILE - для BFILE;

  • OCI_B_CFILE - для CFILE;

  • OCI_B_CLOB - для CLOB;

  • OCI_B_BLOB - для BLOB;

  • OCI_B_ROWID - для ROWID;

  • OCI_B_NTY - для именованных типов данных;

  • OCI_B_CURSOR - для курсоров, созданных ранее с помощью oci_new_cursor().

Пример #1 Пример использования oci_bind_by_name()

<?php
/* oci_bind_by_name example thies at thieso dot net (980221)
  inserts 3 records into emp, and uses the ROWID for updating the 
  records just after the insert.
*/

$conn oci_connect("scott""tiger");

$stmt oci_parse($conn"
                          INSERT INTO 
                                     emp (empno, ename) 
                   VALUES 
                                     (:empno,:ename) 
                            RETURNING 
                                     ROWID 
                                 INTO 
                                     :rid
                                         "
);

$data = array(
              
1111 => "Larry"
              
2222 => "Bill"
              
3333 => "Jim"
             
);

$rowid oci_new_descriptor($connOCI_D_ROWID);

oci_bind_by_name($stmt":empno"$empno32);
oci_bind_by_name($stmt":ename"$ename32);
oci_bind_by_name($stmt":rid",   $rowid, -1OCI_B_ROWID);

$update oci_parse($conn"
                            UPDATE
                                  emp 
                               SET 
                                  sal = :sal 
                             WHERE 
                                  ROWID = :rid
                             "
);
oci_bind_by_name($update":rid"$rowid, -1OCI_B_ROWID);
oci_bind_by_name($update":sal"$sal,   32);

$sal 10000;

while (list(
$empno$ename) = each($data)) {
    
oci_execute($stmt);
    
oci_execute($update);


$rowid->free();

oci_free_statement($update);
oci_free_statement($stmt);

$stmt oci_parse($conn"
                          SELECT 
                                * 
                            FROM 
                                emp 
                           WHERE 
                                empno 
                              IN 
                                (1111,2222,3333)
                              "
);
oci_execute($stmt);
                              
while (
$row oci_fetch_assoc($stmt)) {
    
var_dump($row);
}

oci_free_statement($stmt);

/* delete our "junk" from the emp table.... */
$stmt oci_parse($conn"
                          DELETE FROM
                                     emp 
                                WHERE 
                                     empno 
                                   IN 
                                     (1111,2222,3333)
                                   "
);
oci_execute($stmt);
oci_free_statement($stmt);

oci_close($conn);
?>

Помните о том, что при использовании этой функции, конечные пробелы у строки будут обрезаны. Смотрите следующий пример:

Пример #2 Пример oci_bind_by_name()

<?php
    $connection 
oci_connect('apelsin','kanistra');
    
$query "INSERT INTO test_table VALUES(:id, :text)";

    
$statement oci_parse($query);
    
oci_bind_by_name($statement":id"1);
    
oci_bind_by_name($statement":text""trailing spaces follow     ");
    
oci_execute($statement);
    
/*
     Этот код добавит в базу только строку 'trailing spaces follow', без
     пробелов в конце строки
    */
?>

Пример #3 Пример oci_bind_by_name()

<?php
    $connection 
oci_connect('apelsin','kanistra');
    
$query "INSERT INTO test_table VALUES(:id, 'trailing spaces follow      ')";

    
$statement oci_parse($query);
    
oci_bind_by_name($statement":id"1);
    
oci_execute($statement);
    
/*
     А этот код добавит в базу строку 'trailing spaces follow      ' вместе с
     пробелами в конце строки
    */
?>

Внимание

Использовать magic_quotes_gpc, magic_quotes_runtime или addslashes() вместе с oci_bind_by_name() - это определенно плохая идея, т.к. в этих случаях кавычки будут записаны в базу вместе с данными. oci_bind_by_name() не может отличить "магические кавычки" от тех, что были добавлены намеренно.

Замечание: В версиях PHP ниже 5.0.0 эта функция называлась ocinewcollection(). В PHP 5.0.0 и выше ocinewcollection() является алиасом oci_new_collection(), поэтому вы можете продолжать использовать это имя, однако это не рекомендуется.

Возвращает TRUE в случае успешного завершения или FALSE в случае возникновения ошибки.

Коментарии

Note that there have been some changes on the constant identifiers and the documentation is currently not entirely accurate.

Running the following script;

<?php
foreach (array_keys(get_defined_constants()) as $const) {
    if ( 
preg_match('/^OCI_B_/'$const) ) {
        print 
"$const\n";
    }
}
?>

Under PHP 4.4.0 I get;

OCI_B_SQLT_NTY < renamed to OCI_B_NTY with PHP5
OCI_B_BFILE
OCI_B_CFILEE
OCI_B_CLOB
OCI_B_BLOB
OCI_B_ROWID
OCI_B_CURSOR
OCI_B_BIN

Under PHP 5.0.4 I get;

OCI_B_NTY
OCI_B_BFILE < docs are wrong right now
OCI_B_CFILEE < docs are wrong right now
OCI_B_CLOB
OCI_B_BLOB
OCI_B_ROWID
OCI_B_CURSOR
OCI_B_BIN < it's a mystery
2005-08-16 16:12:13
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
Автор:
This is an example of returning the primary key from an insert so that you can do inserts on other tables with foreign keys based on that value.  The date is just used to provied semi-unique data to be inserted.

$conn = oci_connect("username", "password")
$stmt = oci_parse($conn, "INSERT INTO test (test_msg) values (:data) RETURN test_id INTO :RV");
$data = date("d-M-Y H:i:s");
oci_bind_by_name($stmt, ":RV", $rv, -1, SQLT_INT);
oci_bind_by_name($stmt, ":data", $data, 24);
oci_execute($stmt);
print $rv;
2007-01-11 10:48:19
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
Автор:
This is what the old OCI_B_* constants are now called:
(PHP 5.1.6 win32)

OCI_B_NTY - SQLT_NTY
OCI_B_BFILE - SQLT_BFILEE
OCI_B_CFILEE - SQLT_CFILEE
OCI_B_CLOB - SQLT_CLOB
OCI_B_BLOB - SQLT_BLOB
OCI_B_ROWID - SQLT_RDD
OCI_B_CURSOR - SQLT_RSET
OCI_B_BIN - SQLT_BIN
OCI_B_INT - SQLT_INT
OCI_B_NUM - SQLT_NUM
2007-05-08 16:59:22
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
//Calling Oracle Stored Procedure
//I assume that you have a users table and three columns in users table i.e. id, user, email in oracle
// For example I made connection in constructor, you can modify as per your requirement.
//http://www.devshed.com/c/a/PHP/Understanding-Destructors-in-PHP-5/1/
<?php
class Users{
    private 
$connection;
   
    public function 
__construct()
    {
       
$this->connection oci_connect("scott""tiger"$db); // Establishes a connection to the Oracle server; 
   
}

    public function 
selectUsers($start_index=1$numbers_of_rows=20)
    {
       
$sql ="BEGIN sp_users_select(:p_start_index, :p_numbers_of_rows, :p_cursor, :p_result); END;";
       
$stmt oci_parse($this->connection$sql);

       
//Bind in parameter
       
oci_bind_by_name($stmt':p_start_index'$start_index20);
       
oci_bind_by_name($stmt':p_numbers_of_rows'$numbers_of_rows20);

       
//Bind out parameter
       
oci_bind_by_name($stmt':p_result'$result20); // returns 0 if stored procedure succeessfully executed.

        //Bind Cursor
       
$p_cursor oci_new_cursor($this->connection);
       
oci_bind_by_name($stmt':p_cursor'$p_cursor, -1OCI_B_CURSOR);

       
// Execute Statement
       
oci_execute($stmt);
       
oci_execute($p_cursorOCI_DEFAULT);

       
oci_fetch_all($p_cursor$cursornullnullOCI_FETCHSTATEMENT_BY_ROW);

        echo 
$result;
        echo 
'<br>';
       
var_dump($cursor); // $cursor is an associative array so we can use print_r() to print this data.
        // you can return data from this function to use it at your user interface.
   
}

    public function 
deleteUser($id)
    {
       
$sql ="BEGIN sp_user_delete(:p_id, :p_result); END;";
       
$stmt oci_parse($this->connection$sql);

       
// bind in and out variables
       
oci_bind_by_name($stmt':p_id'$id20);
       
oci_bind_by_name($stmt':p_result'$result20);

       
//Execute the statement
       
$check oci_execute($stmt);

        if(
$check == true)
       
$commit oci_commit($this->connection);
        else
       
$commit oci_rollback($this->connection);

        return 
$result;
    }
   
   
// You can make function for insert ,update using above two functions

}
?>
2008-05-09 12:39:58
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
Dont forget the 5th parameter: $type. It's will slowly your code some times. Eg:

<?php
$sql 
"select * from (select * from b xxx) where rownum < :rnum";
$stmt OCIParse($conn,$sql);
OCIBindByName($stmt":rnum"$NUM, -1);
OCIExecute($stmt);
?>

Below code was slow 5~6 time than not use bind value.Change the 3rd line to:

<?php
OCIBindByName
($stmt":rnum"$NUM, -1SQLT_INT);
?>

will resloved this problem.

This issue is also in the ADODB DB class(adodb.sf.net), you will be careful for use the SelectLimit method.
2009-02-20 05:54:19
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
Sometimes you get the error "ORA-01461: can bind a LONG value only for insert into a LONG column".  This error is highly misleading especially when you have no LONG columns or LONG values.

From my testing it seems this error can be caused when the value of a bound variable exceeds the length allocated.

To avoid this error make sure you specify lengths when binding varchars e.g. 
<?php
oci_bind_by_name
($stmt,':string',$string256);
?>

And for numerics use the default length (-1) but tell oracle its an integer e.g. 
<?php
oci_bind_by_name
($stmt,':num',$num, -1SQLT_INT);
?>
2009-07-20 09:14:29
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
I unfortunately spent the whole day trying to make this work as part of OCI bind_by_name insert:

<?php
     
if(is_numeric($v2)){
       
oci_bind_by_name($stmth$bvar$v2,  -1OCI_B_INT);
      }else{
       
$v2 = (string) $v2;
       
oci_bind_by_name($stmth$bvar$v2, -1SQLT_CHR);
      }
?>

The string field is always inserting correctly w/o any truncation. The string field is a  varchar2(160) CHAR, but the data used to populate it is 40 chars in length.

The numeric part is of Type Number in the database which is being used to store unix time (10 digit seconds since 1970/01/01.

The problem, the insert was truncating to 9 digits with some bogus value not even related to the input i.e., it's not just a matter of dropping the leftmost or rightmost digit, it'll just insert a 9 digit bogus number.

The only way I was able to resolve this for the numeric field was to set the maxlength to 8 (not 10 which is the number of digits in the input): 

<?php
     
if(is_numeric($v2)){
       
oci_bind_by_name($stmth$bvar$v28OCI_B_INT);
      }else{
       
$v2 = (string) $v2;
       
oci_bind_by_name($stmth$bvar$v2, -1SQLT_CHR);
      }
?>

Hopefully you'll see this soon before you expend a lot of time repeating the same problem I had.
2011-09-24 23:03:43
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
It is very important to set up the maxlength of the returning parameter (:r), even when it is returning a number, otherwise the ORA-01460 exception (unimplemented or unreasonable conversion requested) may be raised.
2014-04-17 19:02:39
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
Working with Oracle and raw types in and out worked like the following for me.

<?php
 
/*oracle procedure
  procedure open_session(
    i_instance_id in raw,
    o_session_id out raw,
    o_errcode out number,
    o_errmsg out varchar2
  ); 
  */

  //open database
 
$conn DBOpenDB_DEV_USER );

 
//get session id
 
$sql "begin p_loader.open_session( hextoraw( :instance_id ), :session_id, :errcode, :errmsg ); end;";
 
$stmt oci_parse$conn$sql );
 
$instanceId DB_INSTANCE_ID;
 
oci_bind_by_name$stmt":instance_id"$instanceId1SQLT_CHR );
 
oci_bind_by_name$stmt":session_id"$sessionId16SQLT_BIN );
 
oci_bind_by_name$stmt":errcode"$errcode12SQLT_INT );
 
oci_bind_by_name$stmt":errmsg"$errmsg4000SQLT_CHR );
 
 
oci_execute$stmt );
 
$sessionId bin2hex$sessionId ); //now this is a hex string
 
  //close database
 
DBClose$conn );
?>
2014-09-23 05:54:50
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
I had a query that was working properly at first sight, no errors on execute, nothing, but there were simply no results returned at runtime.

Be careful when putting the database commands into a function and binding your variables there while using oci_fetch_xxx() outside the function.

function sql($conn, $stmt, $var) {
  $stid = oci_parse($conn, $stmt);
  ...
  oci_bind_by_name($stid, ':val', $var);
  ...
}
sql($conn, $q, $var);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);

As you see from the definition of oci_bind_by_name(), $var needs to be passed as reference, so your function has to have this reference ready like this:

function sql($conn, $stmt, &$var) {
  $stid = oci_parse($conn, $stmt);
  ...
  oci_bind_by_name($stid, ':val', $var);
  ...
}

The background is that if you don't pass by reference (in which case $var inside the function is a copy of $var outside the function), then oci_bind_by_name() will work just fine at first glance.
However, since the oci_fetch statements that you use to actually get the data will reference the $var that has ceased to exist when the function finished. In fact, since the varbind seems to be a pointer, that pointer will point to an invalid location at that point and your variables won't be substitued in the SQL.

All this also means that:

1) You have to pass a variable, and not just a value

This doesn't work:

$stid = sql($conn, $q, array('bla'=>'blubb'));

This is better:

$vars = array('bla'=>'blubb');
$stid = sql($conn, $q, $vars);

2) Even when passing as reference to your helper function you cannot use e.g. foreach:

This doesn't work:

function sql($conn, $q, $vars) {
  ...
  foreach ($vars as $k => $v) {
    oci_bind_by_name($stid, $k, $v);
  }
  ...
}

Again, because $k and $v are local variables that will have disappeared once you perform an oci_fetch outside the function.

Instead you have to work the array in a more low-level way like this:

function sql($conn, $q, &$vars) {
  ...
  $stid = oci_parse($conn, $q);
  ...
  reset($vars);
  do {
    if (current($vars)===FALSE) { // end of array
      break;
    }
    $b = oci_bind_by_name($stid, key($vars), current($vars));
    if ($b === FALSE) {
      DIE('Could not bind var');
    }
  } while (each($vars) !== FALSE);
}
$binds = array(':bla1' => 'blubb1',
               ':bla2' => 'blubb2');
$stid = sql($conn, $q, $binds);
$row = oci_fetch_array($stid, OCI_ASSOC+OCI_RETURN_NULLS);

Wherever you oci_bind_by_name(), the pointer to the initial data has to exist from beginning to end.
2016-03-26 21:53:58
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
Please note that in my earlier note about having oci_bind_by_name() in a function, this becomes a little more complicated when returning values like "UPDATE table SET bla='blubb' RETURNING id INTO :id". 

You can do it as follows:

<?php
function sql($q, &$vars_in=array(), &$vars_out=array()) {
  ...
 
$stid oci_parse($conn$q);
  ...
 
reset($vars_in);
  do {
    if (
current($vars_in)===FALSE) {
      break;
    }
   
$b oci_bind_by_name($stidkey($vars_in), current($vars_in));
   
// insert exception handling here
 
} while (each($vars_in) !== FALSE);

 
// VARS TO RETURN
  // we'll fix this to integer type because for now we need this for index IDs
 
foreach ($vars_out as $k => $v) {
   
$b oci_bind_by_name($stid$k$vars_out[$k], -1SQLT_INT);
   
// insert exception handling here
 
}

  ...
}
?>

Use like this:

<?php
$blubb 
'blubb';
$b = array(':bla' => $blubb);
$b_out = array(':id' => ''); // leave value empty
$x sql($q$b$b_out);
$id $b_out[':id'];
?>

(The point is: you would not be able to return anything into $b[':bla'] because $b[':bla'] becomes current($vars_in) inside sql() and cannot be written to.)
2016-03-29 00:11:36
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
Example #7 only shows the binding of a small fixed number of values in an IN clause. There is also a way to bind multiple conditions with a variable number of values.

<?php
$ids 
= array(
   
103,
   
104
);

$conn         oci_pconnect($user$pass$tns);
// Using ORACLE table() function to get the ids from the subquery
$sql          'SELECT * FROM employees WHERE employee_id IN (SELECT column_value FROM table(:ids))';
$stmt         oci_parse($conn$sql);
// Create collection of numbers. Build in type for strings is ODCIVARCHAR2LIST, but you can also create own types.
$idCollection oci_new_collection($conn'ODCINUMBERLIST''SYS');

// Maximum length of collections of type ODCINUMBERLIST is 32767, maybe you should check that!
foreach ($ids as $id) {
   
$idCollection->append($id);
}

oci_bind_by_name($stmt':ids'$idCollection, -1SQLT_NTY);
oci_execute($stmtOCI_DEFAULT);
oci_fetch_all($stmt$return);
oci_free_statement($stmt);

oci_close($conn);

?>
2016-08-24 14:21:56
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
Автор:
Bear in mind that you cannot use reserved words for bind variables. Otherwise you'll get ORA-01745: Invalid host/bind variable name error.
2017-07-24 05:25:32
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
Guys, i've been looking for long time, how to pass clob to and get from procedure
CREATE OR REPLACE PROCEDURE myproc(p1 IN clob, p2 OUT clob);

Here You are an answer:

<?php
        $conn 
oci_connect("TEST""html""//hostname""UTF8");

   
$filename "./clob.txt";
   
$handle fopen($filename"r");
   
$f fread($handlefilesize($filename));
   
fclose($handle);

   
$stid oci_parse($conn"begin myproc(:p1, :p2); end;");
   
$p1 oci_new_descriptor($connOCI_D_LOB);
   
$p2 oci_new_descriptor($connOCI_D_LOB);
   
   
oci_bind_by_name($stid":p1"$p1, -1OCI_B_CLOB);
   
oci_bind_by_name($stid":p2"$p2, -1OCI_B_CLOB);
   
$p1->writeTemporary($fOCI_TEMP_BLOB);
   
oci_execute($stid); -- Figure out OCI_NO_AUTO_COMMIT
    oci_commit
($conn);
    echo 
$p2->load(); 
   
   
$p1    ->close();
   
$p2    ->close();
   
oci_free_statement($stid);
   
oci_close($conn);
?>

And perfect book about "PHP and Oracle" 
http://www.oracle.com/technetwork/topics/php/underground-php-oracle-manual-098250.html
2017-10-19 13:27:52
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
Guys, i've been looking for long time, how to pass clob to and get from procedure
CREATE OR REPLACE PROCEDURE myproc(p1 IN clob, p2 OUT clob);

Here You are an answer:

<?php
        $conn 
oci_connect("TEST""html""//hostname""UTF8");

   
$filename "./clob.txt";
   
$handle fopen($filename"r");
   
$f fread($handlefilesize($filename));
   
fclose($handle);

   
$stid oci_parse($conn"begin myproc(:p1, :p2); end;");
   
$p1 oci_new_descriptor($connOCI_D_LOB);
   
$p2 oci_new_descriptor($connOCI_D_LOB);
   
   
oci_bind_by_name($stid":p1"$p1, -1OCI_B_CLOB);
   
oci_bind_by_name($stid":p2"$p2, -1OCI_B_CLOB);
   
$p1->writeTemporary($fOCI_TEMP_BLOB);
   
oci_execute($stid); -- Figure out OCI_NO_AUTO_COMMIT
    oci_commit
($conn);
    echo 
$p2->load(); 
   
   
$p1    ->close();
   
$p2    ->close();
   
oci_free_statement($stid);
   
oci_close($conn);
?>

And perfect book about "PHP and Oracle" 
http://www.oracle.com/technetwork/topics/php/underground-php-oracle-manual-098250.html
2017-10-19 13:28:40
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
If you are getting "ORA-01722: invalid number error" while inserting/updating a FLOAT value into a NUMBER column, please check the correctness of a binded value format according to the current locale settings. 

Default "american" locale assumes that value send to oracle will be a dot decimal separator (just like 4127.5). But with setlocale('pl_PL.UTF-8') your float number would be represented as 4127,5 and that form will be used while sending data do oracle causing a problem...
That was my case (8 hours of debugging).

You can check your current locale with setlocale(LC_ALL, 0).

What I can recommend as a solutions:
a) do not set locale, or set it to 'C' for a time of sending data;
b) convert float to a string format compatible with current oracle session NLS_NUMERIC_CHARACTERS parameter value. 
For example: when NLS_NUMERIC_CHARACTERS = '.,' float value 4127.5 should be converted to '4127.5'.  Then oracle will catch it correctly even if current locale are set differently.
2019-10-23 02:20:26
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
I am trying to rework ADOdb library calls to OCI, and I wrote this function today which is helping.

function OraQry(&$Results, $Query, $Binds = false) {
  global $xdb;

  $Results = oci_parse($xdb, $Query);

  if($Binds) foreach($Binds as $BindNm => $BindValJunk)
    oci_bind_by_name($Results, $BindNm, $Binds[$BindNm], -1);

  oci_execute($Results, OCI_NO_AUTO_COMMIT);

  return null;
}

This also has similarity to PDO in passing an array of bind variables, with the added benefit that if they are named numerically (starting at zero), then the call to the array() function can be omitted:

OraQry($rs,
  'select status from all_tables where owner=:0 and table_name=:1',
    [$owner, $table_name]);

while($arr = oci_fetch_assoc($rs)) echo $arr['STATUS'] . "\n";
2021-07-21 21:45:48
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html
The note about the PHP var argument being a reference and some kinds of loops not working is very important here.  However, you can make a foreach loop work if you create a temporary variable, use that in the bind and then unset it.  For example:

<?php
foreach ($myarray as $key => $val)  {
   
$value $val;
   
oci_bind_by_name($stid$key$value);
    unset(
$value);
}
?>

This binds each key to the location of $value, but when you unset it after binding, it can be set and used again.

https://www.php.net/manual/en/function.unset.php
2024-02-14 18:08:23
http://php5.kiev.ua/manual/ru/function.oci-bind-by-name.html

    Поддержать сайт на родительском проекте КГБ