0

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?

marc_s
  • 732,580
  • 175
  • 1,330
  • 1,459

3 Answers3

1

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

e.g:

return $query->result();
ahmad
  • 2,709
  • 1
  • 23
  • 27
1

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"

Arzgethalm
  • 516
  • 5
  • 14
  • @ChamaraMaduranga Accept the answer (green tick left to answer) if the answer helped. It'll close the question and help others for future use. – Parag Tyagi Mar 21 '15 at 18:19
0

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

  • thanks Deusmar , but my actual issue is ` $this -> db -> select('`car` As type,id,title,status'); $this -> db -> from('car_product'); $this -> db -> where('status =','P'); $query_car = $this -> db -> get()->result();` codeignator didn't support `'`car` As type` – Chamara Maduranga Mar 21 '15 at 16:11