DanRz Posted July 10, 2022 Share Posted July 10, 2022 Hey! I have the following code in a class.. public function deductCredit(){ $currentAmount = $this->getCredits(); $newAmount = $currentAmount - '1'; $this->dashboard->updateSettings("email_credit", array("count"=>$newAmount)); return $newAmount; } This gets the current credits... deducts 1 and pushes the update back... If I run the function outside of the class it works as expected... however, if I run it within a functions a bit further down the class it always returns -1... Any ideas would be appreciated! Dan Quote Link to comment https://forums.phpfreaks.com/topic/315020-subtract-1-gives-minus-number/ Share on other sites More sharing options...
Barand Posted July 10, 2022 Share Posted July 10, 2022 If it returns -1 then $this->getCredits() must be returning 0 (or false). Quote Link to comment https://forums.phpfreaks.com/topic/315020-subtract-1-gives-minus-number/#findComment-1598112 Share on other sites More sharing options...
mac_gyver Posted July 10, 2022 Share Posted July 10, 2022 aside from something preventing this from working, there's two problems with trying to maintain a value this way - it's not concurrent safe/atomic. if more than one instance of your script is requested at the same time, they will all get the same starting value, modify it, and update it to the same ending value, resulting in only one instance of the value being modified. if you did have a need to do this, you would do it all in one single UPDATE query, which will work properly regardless of how many concurrent instances of the script is running, since the database will get the existing value, modify it, and save it while doing the necessary table locking so that this occurs during one 'atomic' operation. you should insert a row for every transaction that affects a value, so that you will have an audit trail that would let you known if a programming mistake, an accidental key press, or nefarious activity has modified the value. you would simply SUM() the +/- amounts from the relevant rows for any particular account number to get the current amount, just like your bank, credit card, utility account, ... does. Quote Link to comment https://forums.phpfreaks.com/topic/315020-subtract-1-gives-minus-number/#findComment-1598117 Share on other sites More sharing options...
ginerjm Posted July 10, 2022 Share Posted July 10, 2022 And - if you are doing math why are you using a string value to do your decrement??? Quote Link to comment https://forums.phpfreaks.com/topic/315020-subtract-1-gives-minus-number/#findComment-1598118 Share on other sites More sharing options...
Recommended Posts
Join the conversation
You can post now and register later. If you have an account, sign in now to post with your account.