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',
);
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);
?>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With