从两个表中选择数据时出错

时间:2014-03-21 09:45:16

标签: php mysql codeigniter

Error Number: 1096

没有使用过表格 SELECT *

$where = array();
            if($category){
                $where[] = 'subcategories.categories_id = '.$category;
            }
            if($value){
                $where[] = "subcategories.name LIKE '%".$value."%'";
            }
            $where = implode('and', $where);
            $this->db->query("select subcategories.*, categories.name as catname FROM subcategories JOIN categories ON categories.id = subcategories.categories_id where ".$where);
            $query = $this->db->get();

我正在加入两个表类别和子类别与动态where condition.same查询在phpmyadmin中工作但在codeigniter中得到错误,提前感谢

3 个答案:

答案 0 :(得分:2)

尝试

$query = $this->db->query("Your Query Here");
$query = $query->result();
print_r($query);

并编辑你喜欢的地方

$where = '';
if($category){
     $where .= 'subcategories.categories_id = '.$category;
}
if($value){
     if($category) {
         $where .= " AND ";
     }
     $where .= "subcategories.name LIKE '%".$value."%'";
}

答案 1 :(得分:2)

请尝试遵循codeigniter的约定。 根据您的要求,这是您的解决方案:

$this->db->select('subcategories.*, categories.name as catname');
$this->db->from('subcategories');
$this->db->join('categories', 'categories.id = subcategories.categories_id');
if($category)
{
    $this->db->where('subcategories.categories_id', $category); 
}
if($value)
{
    $this->db->like('subcategories.name', $value,'both'); 
}
$query = $this->db->get()->result();

答案 2 :(得分:0)

您可以按照 codeigniter 约定来准备SQL查询

试试这种方式,

$this->db->select("subcategories.*, categories.name as catname", false)
            ->join("categories", "categories.id = subcategories.categories_id")
                ->where("subcategories.categories_id", $category)
                    ->like("subcategories.name", $value, "both");
$query = $this->db->get("subcategories")->result();