phpmysqlcodeigniterwhere-clausequery-builder

CodeIgniter's get() method doesn't receive WHERE conditions as expected


I have gone through many questions about joining 3 tables in Codeigniter, but I am stuck in these lines of coding that includes returning products array.

function products_sorter($region)
{
    $this->db->select('*');
    $this->db->from('wiyo_products');
    $this->db->join('wiyo_products_distribution', 'wiyo_products.id = wiyo_products_distribution.product_id');
    $this->db->join('wiyo_regions', 'wiyo_regions.id = wiyo_products_distribution.region_id');
    $query = $this->db->get(array('wiyo_regions.slug' => $region));
    
    if ($query->num_rows() > 0) {
        return $query;
    }
}

But I am getting error which look like this

A Database Error Occurred

Error Number: 1103

Incorrect table name ') JOIN '

SELECT * FROM (`wiyo_products`, `) JOIN `wiyo_products_distribution` ON `wiyo_products`.`id` = `wiyo_products_distribution`.`product_id` JOIN `wiyo_regions` ON `wiyo_regions`.`id` = `wiyo_products_distribution`.`region_id`

What sort of error is this? How to solve this?


Solution

  • You are getting the error because of the improper use of the Active Record get function, which uses the table name as the first parameter.

    http://ellislab.com/codeigniter/user-guide/database/active_record.html

    As you appear to be passing an array into the get function, I'm guessing you want the get_where function instead?

    Try the below - removing the from line in your current query and placing the table name as the first parameter in the get_where function, with your current array being passed in as the second parameter:

    function products_sorter($region) {
        $this -> db -> select('*');
        $this -> db -> join('wiyo_products_distribution', 'wiyo_products.id = wiyo_products_distribution.product_id');
        $this -> db -> join('wiyo_regions', 'wiyo_regions.id = wiyo_products_distribution.region_id');
        $query = $this -> db -> get_where('wiyo_products' array('wiyo_regions.slug' => $region));    
        if ($query -> num_rows() > 0) {
            return $query;
    
        }    
    }
    

    Hope that helps!