简体   繁体   English

php codeigniter选择查询

[英]php codeigniter select query

This is the my original SQL query 这是我原来的SQL查询

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 现在,我想使用CodeIgniter运行此查询,因此我尝试使用此查询

$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()方法,而无需为此使用queryBuilder。

$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 https://ellislab.com/codeigniter/user-guide/database/active_record.html

$this->db->select(); $ 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" 注意:当您将可选参数设置为“ false”时,您将不会受到反引号的保护

Try removing '=', : 尝试删除'=',:

ex: $status = 'Chamara' 例如:$ status ='Chamara'

 $this->db->where("status",$status); 

//Produces: WHERE 'status' = 'Chamara' //产生: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'); 建议2:使用$ this-> db-> get('van_product'); instead of 代替

 $this -> db -> from('van_product'); $query_van = $this -> db -> get()->result(); 

// Produces: SELECT * FROM van_product //产生:SELECT * FROM van_product

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM