Question

How could I simplify this update instruction? Whenever a client buys an item it will update the sales with 1.

$this->db->query('SELECT amount FROM shop_items WHERE itemid='.$itemid.'');   
$new_amount = $item->amount+1;
    if(!$this->db->query('UPDATE shop_items SET amount='.$new_amount.' WHERE itemid='.$itemid.'')):
    return false;
    endif;

Can't I make it more simple so there are less lines, for example:

if(!$this->db->query('UPDATE shop_items SET amount=_current_value_+1 WHERE itemid='.$itemid.'')):
return false;
endif;

is this possible? if not thanks anyway

Was it helpful?

Solution

What about using the following SQL query :

update shop_items
set amount = amount + 1
where itemid = 123

Basically, in just one SQL query, you set the amount to the previous value it had, plus one.
No need for two queries ;-)


Integrating this in your PHP code should give you something that looks like this :

if (!$this->db->query('UPDATE shop_items SET amount=amount+1 WHERE itemid='.$itemid.'')) :
    return false;
endif;

Note : I just replaced your _current_value_ by the name of the field that you're working on : amount.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top