用于'IN'语句的PHP OCI8绑定(未知数量)参数

时间:2012-10-25 09:21:00

标签: php sql oci

对于SQL IN子句,在使用PHP OCI8绑定SQL时如何处理未知数量的参数?

例如,给出以下查询

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

和要绑定的变量数组

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

另外需要注意的是,在我的特定情况下,输入array($bind_array)可能包含也可能不包含bind元素的子数组。它也可以是以下

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

$bind_array = array(
    ':id_1' => '1',
    ':id_2' => '5',
);

2 个答案:

答案 0 :(得分:3)

一种方法是在IN子句中绑定少量固定数量的值,如oci_bind_by_name的文档中所述。还有一种解决方案可以使用可变数量的值绑定多个条件。

<?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);

?>

答案 1 :(得分:0)

您应该将数组与另一个函数绑定 - oci_bind_array_by_name

http://php.net/manual/en/function.oci-bind-array-by-name

你不能用oci_bind_by_name替换:变量与数组对象 http://php.net/manual/en/function.oci-bind-by-name.php