php – Problem concatenating query in PDO

Question:

Goodnight,

I have a query that contains multiple choices by checkbox and Selects and I'm trying to concatenate the query to search depending on the user's choice but give me error I don't know what I can be doing wrong I'll leave the code I currently have for you to see and if possible tell me what i could be doing wrong.

Code

 $result_keywords = "";

    if(isset($_GET['pesquisa'])){

        $sql = "SELECT * FROM estabelecimentos WHERE keywords_pesquisa LIKE :keywords_pesquisa OR titulo LIKE :titulo AND activo = :activo ";
        $result_keywords = $conexao->prepare($sql); 

    }

    $checado = implode(",", $_POST['servicos']);
    if(isset($_POST['servicos'])){

        $sql .= "AND servicos = :servicos ";
        $result_keywords = $conexao->prepare($sql); 

    }

    if(isset($_GET['pesquisa'])){

    $result_keywords->bindValue(':activo', 1, PDO::PARAM_INT); 
    $result_keywords->bindValue(':titulo', "%{$_GET['pesquisa']}%", PDO::PARAM_STR); 
    $result_keywords->bindValue(':keywords_pesquisa', "%{$_GET['pesquisa']}%", PDO::PARAM_STR);  
    }
    if(isset($_POST['servicos'])){

        $result_keywords->bindValue(':servicos', implode(",", $_POST['servicos']), PDO::PARAM_STR); 

    }
$result_keywords->execute(); 
$row_keywords = $result_keywords->fetchAll(PDO::FETCH_ASSOC);   

Answer:

Missing to use parentheses in the query. Try this:

$sql = "SELECT * FROM estabelecimentos WHERE keywords_pesquisa LIKE (:keywords_pesquisa)
        OR titulo LIKE (:titulo) AND activo = :activo ";

Don't forget to make sure all your search terms in keywords_pesquisa and titulo are separated by a comma.

Scroll to Top