MySQL Search with filter select option

1

I have a question. I have a php page with several select option to filter a search in the database. However, I can not use the values selected in the query. I made as an example I saw in another site, an array to store only the values of the select option that were filled and concatenate that array in the 'where' clause of my query ... without success!

$tipoentradalog = post('tipoentradalog');
    $usuario = post('usuario');
    $codcliente = post('codcliente');

    $where = Array();
    if ($tipoentradalog) {
        $where[] = " 'tipoentradalog' = '{$tipoentradalog}'";
    }
    if ($usuario) {
        $where[] = " 'usuario' = '{$usuario}'";
    }

    if ($codcliente) {
        $where[] = " 'codcliente' = '{$codcliente}'";
    }

$sql = "select
                            l.datacriacao,
                            tl.nome as tipo,
                            l.descricao,
                            cli.nome as cliente,
                            us.nome as usuario,
                            l.codigo
                            from log l
                            inner join cliente cli on cli.codcliente=l.codcliente
                            inner join usuario us on us.codusuario=l.codusuario
                            inner join empresa emp on emp.codempresa=l.codempresa
                            inner join tipoentradalog tl on tl.codtipoentradalog=l.codtipoentradalog;";
            if(sizeof($where)) {
                $sql .= ' WHERE ' . implode(' AND ', $where);
            }
            $rst = my_query($connR, $sql);

Does anyone know how to help me? Thank you

    
asked by anonymous 03.08.2015 / 21:23

1 answer

1

The problem is that you have put single quotes in the field names, and this causes you to make an invalid comparison.

Correct as below, that your query will work:

if ($tipoentradalog) {
        $where[] = " tipoentradalog = '{$tipoentradalog}'";
}
if ($usuario) {
        $where[] = " usuario = '{$usuario}'";
}
if ($codcliente) {
        $where[] = " codcliente = '{$codcliente}'";
}

If you want to put quotation marks, in this case, you should use the crass:

if ($tipoentradalog) {
        $where[] = " 'tipoentradalog' = '{$tipoentradalog}'";
}
if ($usuario) {
        $where[] = " 'usuario' = '{$usuario}'";
}
if ($codcliente) {
        $where[] = " 'codcliente' = '{$codcliente}'";
}
    
04.08.2015 / 19:27