Handle an array key?

0

I need to manipulate a key that is passed as a parameter in this query :

$Read->FullRead("SELECT DISTINCT ".DB_CONTAS." WHERE 
                 contas_status = 1 '{$FilterAdd} ", "{$FilterValues}");'

The var_dump {$FilterAdd} returns this:

array (size=3)
  'contastipodetalhe' => string '1' (length=1)
  'anobase' => string '2016' (length=4)
  'mesbase' => string '12' (length=2)

Well, what's complicated about this?

I need, if the user selects 1 or more filter fields, that my array receives only the fields that were selected and if any of these fields is anobase and / or mesbase , I have to insert a year and month into the select to extract the year and month so that it can compare with the value selected in the field.

Example:

My current query looks like this:

SELECT DISTINCT contas 
 WHERE contas_status = 1 AND 
       contastipodetalhe = :contastipodetalhe AND 
       anobase = :anobase AND mesbase = :mesbase '

I need it to look like this:

SELECT DISTINCT contas 
 WHERE contas_status = 1 AND 
       contastipodetalhe = :contastipodetalhe AND 
       year(anobase) = :anobase AND month(mesbase) = :mesbase '

Note that I use year and month , this I am not able to send in the vector at this time that it mounts {$FilterAdd} :

if ($TranspFilter):     
    foreach ($TranspFilter as $fKey => $fValue):     
           $FilterAdd .= " AND {$fKey} = :{$fKey}";     
    endforeach;
    $_SESSION['transp_filter'] = null;
endif; 

I've already thought about making a if to know if the selected value is month or year and then try to change the key of vetor , but not rolled, if anyone knows where I went wrong or give me another solution I thank:

if ($TranspFilter):     
    foreach ($TranspFilter as $fKey => $fValue):
      if($fKey['anobase']):
          $FilterAdd .= "AND year({$fKey}) = :({$fKey})";
      endif;
      if($fKey['mesbase']):
          $FilterAdd .= "AND month({$fKey}) = :({$fKey})";
      endif;     
      $FilterAdd .= " AND {$fKey} = :{$fKey}";     
    endforeach;
    $_SESSION['transp_filter'] = null;
endif;
    
asked by anonymous 04.01.2017 / 20:48

1 answer

2

Your code is incorrect. You are treating the string as if it were an array.

Correcting:

if ($TranspFilter) {

    foreach ($TranspFilter as $fKey => $fValue) {
        if ($fKey == 'anobase') {
            $FilterAdd .= "AND year({$fKey}) = :({$fKey})";
        } else if ($fKey == 'mesbase') {
            $FilterAdd .= "AND month({$fKey}) = :({$fKey})";
        } else {
            $FilterAdd .= " AND {$fKey} = :{$fKey}";
        }
    }
    $_SESSION['transp_filter'] = null;

}

PS: I rewrote the blocks in the conventional way, since there is no block of HTML and I do not think it's worth it to lose the readability of the code written in this way idly.

    
04.01.2017 / 23:32