How can I make custom SQL with order by in codeign

2019-04-17 05:38发布

问题:

My code is here Sql Query :

$sql ="select * from products where status='1' AND country='5' AND product_price > "50" AND product_price <= "100" order by product_id desc";
$product=$this->db->query($sql)->result_array();

view all products by using customs SQL but still not showing order by desc.

回答1:

Try this:

$sql = "SELECT * FROM `products` WHERE `status`=1 AND `country`=5 AND `product_price` > 50 AND `product_price` <= 100 ORDER BY `product_id` DESC";
        $product = $this->db->query($sql)->result_array();


回答2:

It's better to use built-in Codeigniter Query-builder:

$this->db->select('*');
$this->db->where([
    'status'    => 1,
    'country'   => 5,
    'product_price >' => 50,
    'product_price <=' => 100,
]);
$this->db->order_by('product_id', 'DESC');
$this->db->get('products');
$product = $this->db->result();


回答3:

You can try this solution for your problem :

$query = $this->db->query('select * from products where status='1' AND country='5' AND product_price > "50" AND product_price <= "100" order by product_id desc');
$row_array = $query->result_array();

I Hop it will help you.



回答4:

Try this

$this->db->from('products');
$this->db->where("status='1' AND country='5' AND product_price > '50' AND product_price <= '100'", null, false);
$this->db->order_by("product_id", "desc");
$query = $this->db->get(); 
return $query->result_array();


回答5:

Please try below code:

$this->db->select('products.*');
$this->db->from('products');
$sql="status='1' AND country='5' AND (product_price > '50' AND product_price <= '100')";
$this->db->where($sql, NULL, FALSE)->order_by("product_id", "DESC");

$products_query = $this->db->get();

$products_info_array = array();

$products_info_array = $products_query->result_array();

return $products_info_array;


回答6:

Can you "describe" type the table? If the field "product_id" is text (Example: VARCHAR), then it will never follow the order asc/desc..

Sorry My English.. Good work!