Search code examples
phpmysqlsqlphalconphalcon-orm

Passing variable in conditions of method find() in Phalcon Framework


I'm receiving a variable in my controller and I want make a bind query with the search variable, I try this:

$search = $this->request->getPost('term');

                    $item = Item::find(
                            [
                                    'columns' => 'name',
                                    'conditions' => "name LIKE :searchT: ",
                                    'bind' => [
                                            'searchT' => '%'.$search.'%',  
                                    ],
                            ]
                            );

This code above is returning items that does not match with the LIKE restriction.

If I pass the string literally works fine:

$item = Item::find(
                            [
                                    'conditions' => "name LIKE '%Os%' ",
                                    'columns' => 'name',
                                    'limit' => 10,
                            ]
                            );

JQuery:

<script type="text/javascript">
$( function() {
    $("#itemSearch").autocomplete({
        source: function ( request, response ) {
            $.ajax({
                type: "POST",
                url: "/item/search",
                dataType: "json",
                data: { 
                    term: request.term    
                },
                contentType: "application/json",
                success: function(data) {
                    response(data);
                }
            });
        },
        minLength: 2
    })
})
</script>

Solution

  • My $search was empty and in my JQuery I needed add a header in ajax:

    ...
    source: function ( request, response ) {
                $.ajax({
                    type: "POST",
                    headers: {
                        'Content-Type': 'application/x-www-form-urlencoded'
                    },  
    ...
    

    Thanks @Abhik Chakraborty