phpmysqlphalconphalcon-orm

Sql operator "and" and "or" not working correctly


When I run this code there seems to be a problem with the Boolean and and or operations:

$ne = News::find(['conditions' => 'title_md = "' . htmlspecialchars($_post['title_md']) . '"  OR alias = "'.$item->alias.'" AND id !=  ' . $id])->toArray();

The condition inside if(count($ne) < 1) returns true, but I need to get false because id is not currently taken.


Solution

  • Here is the correct query using Phalcon's ORM full potential.

    $ne = News::find([
        'conditions' => '(title_md = :title: OR alias = :alias:) AND id != :id:',
        'bind' => [
            'title' => $_POST['title_md'],
            'alias' => $item->alias,
            'id' => $id,
        ]
    ])->toArray();
    

    As the guys above mentioned you have to be more careful when binding parameters to avoid SQL injection. More examples and howto's in the docs: https://docs.phalconphp.com/zh/3.2/db-models#binding-parameters