Search code examples
phpmysqlcodeigniteractiverecordphpactiverecord

An array of conditions for phpactiverecord


I have so many combinations of conditions that could possibly go into a db call that I can't possibly make a separate call for each one. I'd have way too many if/else statements.

So I wanted to instead push conditions into an array to dynamically build both conditional statement and values being passed in. So:

    $cond_values = array();
    $cond_values[] = $lender->id;
    $cond_string = "lender_id = ?";

    if (something) {
      $cond_string .= " AND search_id =?";
      $cond_values[] = $search_id; 
    }
    if (something_else) {
      $cond_string .= " AND cust_id =?";
      $cond_values[] = $cust_id; 
    }

    $matches = Match::all(array(
      "select" => $select,
      "conditions" => array($cond_string, $cond_values),
      "order" => $order,
      "joins" => $joins
    ));

But this only works if $cond_values has 0 or 1 elements in it. More than one value and I get a "No bound parameter for index 1" error. It seems that it would only work if I did:

    $matches = Match::all(array(
      "select" => $select,
      "conditions" => array($cond_string, $cond_values[0],$cond_values[1] ),
      "order" => $order,
      "joins" => $joins
    ));

But the amount of values would vary so I couldn't do that. I'd appreciate any insight.


Solution

  • Try this: use array_unshift() to push your $cond_string onto the beginning of your $cond_values array and then pass that array to Match::all():

    $cond_values = array();
    $cond_values[] = $lender->id;
    $cond_string = "lender_id = ?";
    
    if (something) {
      $cond_string .= " AND search_id =?";
      $cond_values[] = $search_id; 
    }
    if (something_else) {
      $cond_string .= " AND cust_id =?";
      $cond_values[] = $cust_id; 
    }
    
    array_unshift($cond_values, $cond_string);
    
    $matches = Match::all(array(
      "select" => $select,
      "conditions" => $cond_values,
      "order" => $order,
      "joins" => $joins
    ));