Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP OCI8 bind (unknown number of) params for 'IN' statement

For SQL IN clause, how do I handle an unknown number of parameters when binding SQL with PHP OCI8?

For example, given the following query

select * from table1
where id > :id_1
and id in (:id_array_of_unknown_size)

and the array of variables to bind

$bind_array = array(
    ':id_1' => '1',
    ': id_array_of_unknown_size' => array('7','2','5',),
);

Also its important to note that in my particular situation the input array($bind_array) may or may not contain a sub-array for the bind element. It could just as well be the following

select * from table1
where id > :id_1
and id !=  :id_2

and

$bind_array = array(
    ':id_1' => '1',
    ':id_2' => '5',
);
like image 233
beresfordt Avatar asked Oct 25 '12 09:10

beresfordt


1 Answers

One way is the binding of a small fixed number of values in an IN clause like described in the docs of oci_bind_by_name. There is also a solution 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, -1, SQLT_NTY);
oci_execute($stmt, OCI_DEFAULT);
oci_fetch_all($stmt, $return);
oci_free_statement($stmt);

oci_close($conn);

?>
like image 140
h18c Avatar answered Oct 06 '22 03:10

h18c