This is the my original SQL query
select 'car' as type,id,title,status from car_product
union
select 'van' as type,id,title,status from van_product
Now I want to run this query using CodeIgniter, so I try to use this one
$this -> db -> select('`car` As type,id,title,status');
$this -> db -> from('car_product');
$this -> db -> where('status =',$status);
$query_car = $this -> db -> get()->result();
$this -> db -> select('`van` As type,id,title,status');
$this -> db -> from('van_product');
$this -> db -> where('status =',$status);
$query_van = $this -> db -> get()->result();
return array_merge($query_car, $query_van);
but it's not working, please can you help?
You can use ->query() method directly without using queryBuilder for this.
$query = $this->db->query("select 'car' as type,id,title,status from car_product union select 'van' as type,id,title,status from van_product");
Then you can deal it as you deal with your other queries
eg:
return $query->result();
if you want to do it the active record way, use this one.
$this -> db -> select('"car" type,id,title,status',false);
$this -> db -> from('car_product');
$this -> db -> where('status =',$status);
$query_car = $this -> db -> get()->result();
$this -> db -> select('"van" type,id,title,status',false);
$this -> db -> from('van_product');
$this -> db -> where('status =',$status);
$query_van = $this -> db -> get()->result();
return array_merge($query_car, $query_van);
https://ellislab.com/codeigniter/user-guide/database/active_record.html
$this->db->select(); has an optional second parameter that enables you to use compound select statement when needed.
Note: you will not be protected against backticks when you set the optional parameter to "false"
Try removing '=', :
ex: $status = 'Chamara'
$this->db->where("status",$status);
//Produces: WHERE 'status' = 'Chamara'
Suggest: You can use arrays. Maybe in future you'll need to set more than one condition
$condition = array("status"=>$status); $this->db->where($condition);
Suggest 2: Use $this->db->get('van_product'); instead of
$this -> db -> from('van_product'); $query_van = $this -> db -> get()->result();
// Produces: SELECT * FROM van_product
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.