【问题标题】:PHP OCI8 bind (unknown number of) params for 'IN' statement'IN'语句的PHP OCI8绑定(未知数量)参数
【发布时间】:2012-10-15 10:47:04
【问题描述】:

对于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) 可能包含也可能不包含绑定元素的子数组。也可以是下面的

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

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

【问题讨论】:

  • 可以在oci中绑定IN吗?我认为在 PDO 中你不能绑定到 IN

标签: php sql oracle-call-interface


【解决方案1】:

一种方法是在 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);

?>

【讨论】:

    【解决方案2】:

    你应该用另一个函数绑定一个数组 - oci_bind_array_by_name

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-23
      • 1970-01-01
      • 2013-02-09
      • 2011-08-29
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多