Search code examples
phpbehaviorclausecakephp-2.8

Strange behaviour of IN clause in Cakephp 2.8.2


I have created multiple checkbox as follow.

 $forms  = $this->wondr->m('WApplication.ApplicantForms')->find('list', array('conditions' => array('facility_id' => $this->wondr->facility['Facility']['id']), 'contain' => array()));

    $event->result['forms'] = $event->subject()->Form->input(
            'forms', array(
                'multiple'   => 'checkbox',
                'options' => $forms,
                'class'  => 'form-control',
                'label'  => __('Forms'),
            )
       );

It works fine when I chose multiple check box but when I chose only single check box it throws error

   $forms  = $this->wondr->m('WApplication.ApplicantForms')->find('list', array('conditions' => array('facility_id' => $this->wondr->facility['Facility']['id'],
        'ApplicantForms.id IN '=> $event->data['requestQuery']['forms']
    ), 'contain' => array()));

CakePHP automatically converting IN() to IN = () for single id.

Error: SQLSTATE[42000]: Syntax error or access violation: 1064 You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near '= ('595b5fab-97d4-4c59-a41a-013fac120009')' at line 1

SQL Query: SELECT `ApplicantForms`.`id`, `ApplicantForms`.`name` FROM `wondr`.`applicant_forms` AS `ApplicantForms` WHERE `facility_id` = '58ecb98f-92cc-4a90-a692-0026ac120005' AND `ApplicantForms`.`id` IN = ('595b5fab-97d4-4c59-a41a-013fac120009')

Can somebody please help?

Thanks in advance


Solution

  • Just replace:

    $forms  = $this->wondr->m('WApplication.ApplicantForms')->find('list', array('conditions' => array('facility_id' => $this->wondr->facility['Facility']['id'],
        'ApplicantForms.id IN '=> $event->data['requestQuery']['forms']
    ), 'contain' => array()));
    

    By:

    $forms  = $this->wondr->m('WApplication.ApplicantForms')->find('list', array('conditions' => array('facility_id' => $this->wondr->facility['Facility']['id'],
        'ApplicantForms.id'=> (array)$event->data['requestQuery']['forms']
    ), 'contain' => array()));
    

    In other words, remove the IN and make sure that $event->data['requestQuery']['forms'] is an array (if you have a doubt, you could first var_dump it).

    Source: https://stackoverflow.com/a/9445104/978690