Welcome Guest, Not a member yet? Register   Sign In
set sql variable before main query
#1

Is it possible to set sql variable before other queries?(not $this->db->query())

I'd like to do something like this.


PHP Code:
$this->db->query("SET @min_id := (SELECT min_id FROM shop_parameter)");
$this->db->select('item_id');
$this->db->from('products');
$this->db->where('(item_id > @min_id',NULL,FALSE);
$this->db->where(array('item_stat >'=>10));
$query=$this->db->get();
foreach(
$query->result() as $r){
   $products[$r->item_id]=$r; }

Reply
#2

@ash-f,

Yes, it is possible to set sql variable before other queries. The catch is...not the way you have it in your example. There are a couple of ways that you could do it but you would have to use $this->db->query(). With one of those ways, you could actually do it in one query but again it is using the $this->db-query();
Reply
#3

PHP Code:
$this->db->where('(item_id > @min_id',NULL,FALSE); 

Are you missing a parentheses /  bracket here?
What did you Try? What did you Get? What did you Expect?

Joined CodeIgniter Community 2009.  ( Skype: insitfx )
Reply
#4

(02-09-2019, 05:16 AM)InsiteFX Wrote:
PHP Code:
$this->db->where('(item_id > @min_id',NULL,FALSE); 

Are you missing a parentheses /  bracket here?

That is a typo created when I copy&pasted from the original code.
In the original code, I used (item_id > @min_id AND item_id < @max_id)

Reply
#5

(02-08-2019, 05:46 PM)php_rocs Wrote: @ash-f,

Yes, it is possible to set sql variable before other queries.  The catch is...not the way you have it in your example.  There are a couple of ways that you could do it but you would have to use $this->db->query().  With one of those ways, you could actually do it in one query but again it is using the $this->db-query();

Thanks.
I saw something similar and they are using transaction with multiple $this->db-query().
So is that the standard way?
Reply
#6

(This post was last modified: 02-13-2019, 09:57 AM by ash-f. Edit Reason: wrong code )

Ok, I've used two successive $this->db->query()




Code:
$randomitem=array();
$valquery = "SELECT @rid := FLOOR(1+RAND()*item_id) FROM products ORDER BY item_id DESC LIMIT 1";
$this->db->query($valquery);
$mainquery  = "SELECT item_id FROM products WHERE item_id < @rid AND item_stat > 10 ORDER BY item_id DESC LIMIT 2";
$query = $this->db->query($mainquery);
foreach($query->result() as $r){ $randomitem[]=$r->item_id; }
Reply
#7

@ash-f,

Documentation for future reference (of query results)... https://codeigniter.com/user_guide/datab...ry-results
Reply
#8

(02-13-2019, 09:27 PM)php_rocs Wrote: @ash-f,

Documentation for future reference (of query results)... https://codeigniter.com/user_guide/datab...ry-results

Thank you
Reply




Theme © iAndrew 2016 - Forum software by © MyBB