How to use variable in where function

How to use variable in where function

cha59cha59 Posts: 87Questions: 23Answers: 0

I want to filter my data based on a variable, so that I can reuse the filter for the different values of 'hold'. It works if I put in a number like 5, but if I try to post the value of the variable 'hold', it doesn't work. What am I doing wrong?
I've tried session, i've tried a simple variable like $x, but I cannot get the value of the variable over to ':hold'. It will only work if it has a number like 5.

    //This works
    ->where( function ( $q ) {
    $q->where( 'id', '(SELECT id_budget FROM budget_hold WHERE id_hold = :hold)', 'IN', false );
    $q->bind( ':hold', 5 );
    } )   

    /*This doesn't work
    ->where( function ( $q ) {
    $q->where( 'id', '(SELECT id_budget FROM budget_hold WHERE id_hold = :hold)', 'IN', false );
    $q->bind( ':hold', '%'.$_POST['hold'].'%' );
    } )*/  
  
    ->process( $_POST )
    ->json();

This question has an accepted answers - jump to answer

Answers

  • rf1234rf1234 Posts: 2,808Questions: 85Answers: 406
    Answer ✓
    $q->bind( ':hold', '%'.$_POST['hold'].'%' );
    

    will probably only work in a LIKE statement. Haven't tested it. Why are you using '%' which you don't in your hard coded example? Are you sure to have the POST variable filled?

    This works in my coding - just as an example:

    ->where( function ( $q ) {        
        $q ->where( 'id', getValidIdsForUser($_SESSION['id'], 'filtr'), 'IN', false );
        $q ->where( 'id', getValidIdsForContract($_SESSION['SelectedContractId'], 'filtr'), 'IN', false );
        $q ->where( 'id',
            '( SELECT DISTINCT contract_has_filtr.filtr_id  
                 FROM contract_has_filtr  
                WHERE contract_has_filtr.contract_id = :contract_id
            )', 'NOT IN', false);        
        $q ->bind( ':contract_id', $_SESSION['SelectedContractId'] );
    } )
    
  • cha59cha59 Posts: 87Questions: 23Answers: 0

    Hi rf234
    Thanks a lot for answer and your example. Now it works. Saved my day.

This discussion has been closed.