Shivam Sharma
Shivam Sharma

Reputation: 1597

Abnormal behaviour in OCI_BIND_BY_NAME

I was using the following code to bind variables using oci_bind_by_name but getting returned only single row even though multiple rows were available.

<?php 
    $queryArr = array(11423,24242,2463,23434);
    $sqlarr = array();
    for ($i = 0; $i < count($queryArr); $i++) {
        array_push($sqlarr, ":B$i");
    }
    $sqlstr = implode(",", $sqlarr);
    $sql = "SELECT COL1, COL2, STATUS FROM TAB1 WHERE P_KEY = :USR_ID AND S_COL IN (" . $sqlstr . ") ORDER BY STATUS";
    $this->sth = oci_parse($this->con, $sql);
    oci_bind_by_name($this->sth, ":USR_ID", $usrid);
    for ($i = 0; $i < count($queryArr); $i++) {
        $bid = $queryArr[$i];
        oci_bind_by_name($this->sth, ":B$i", $bid);
    }
    oci_execute($this->sth);
?>

After spending 3 hours finding the error in the code I found that the problem is with OCI_BIND_BY_NAME. I changed the above code as below and I was getting all the rows now.

<?php 
    $queryArr = array(11423,24242,2463,23434);
    $sqlarr = array();
    for ($i = 0; $i < count($queryArr); $i++) {
        array_push($sqlarr, ":B$i");
    }
    $sqlstr = implode(",", $sqlarr);
    $sql = "SELECT COL1, COL2, STATUS FROM TAB1 WHERE P_KEY = :USR_ID AND S_COL IN (" . $sqlstr . ") ORDER BY STATUS";
    $this->sth = oci_parse($this->con, $sql);
    oci_bind_by_name($this->sth, ":USR_ID", $usrid);
    for ($i = 0; $i < count($queryArr); $i++) {
    //Changed code --START--
        $bindName = ":B".$i;
        oci_bind_by_name($this->sth, $bindName, $queryArr[$i]);
    //Changed code --END--
    }
    oci_execute($this->sth);
?>

Can someone please explain the reason behind this...?

So as a summary:

When creating a variable by appending string and using it in OCI_BIND_BY_NAME then it's working fine but when I am directly appending string in the function then it's not working correctly. Also, it's not giving any error message. It's getting executed but returning only single row.

Upvotes: 1

Views: 187

Answers (1)

Christopher Jones
Christopher Jones

Reputation: 10506

Your first example is binding $bid in each iteration, i.e the same variable location (memory address) is reused. See the related example 'Example #3 Binding with a foreach() loop' in the oci_bind_by_name() documentation:

foreach ($ba as $key => $val) {

    // oci_bind_by_name($stid, $key, $val) does not work
    // because it binds each placeholder to the same location: $val
    // instead use the actual location of the data: $ba[$key]
    oci_bind_by_name($stid, $key, $ba[$key]);
}

Upvotes: 3

Related Questions