Reputation: 253
This part of PHP and SQL is totally new to me where I need to use maths to update a table.
I currently have a table avis_credits with one row only in this table
The table deducts credits as the user uses the system from qty_credits, but i want to be able to add additional credits to his account as per example:
Client has currently 10 credits left he purchases 100 credits so the system must take the current credits and add the 100 to it giving me the 110 credits. I am doing this currently manual adding it my side and updating the table with this expresion.
"UPDATE avis_credits SET credits='$qty_credit'";
What I would like is that the system looks up the current credits and adds the new credits to the row.
I have tried this
"UPDATE avis_credits SET credits='<?php echo qty_credit?> + $qty_credit'";
But it is not working at all. Is it because I am trying to do too many functions in the one string? Or is it because The maths equation is wrong as I have no idea how to write it?
Upvotes: 1
Views: 105
Reputation: 19528
On your first query you're not doing any math you are purely changing it to the value of your variable:
"UPDATE avis_credits SET credits='$qty_credit'";
So credits becomes the value of $qty_credit
.
On your second query <?php echo qty_credit?>
this is wrong, you're trying to open another php tag on an already open one and you don't use the $
on the variable and then you try to sum the variable so it gives you an error.
"UPDATE avis_credits SET credits='<?php echo qty_credit?> + $qty_credit'";
This will sanitize your input and sum the value of credits with the addition of value of your variable $qty_credit
:
$sql = sprintf("UPDATE avis_credits SET credits = credits + '%s'",
mysql_real_escape_string($qty_credit));
As a side note, you may want to specify an ID of the account you want to deposit the additional credit otherwise the above rule will increase that credit for ALL rows.
$sql = sprintf("UPDATE avis_credits SET credits = credits + '%s' WHERE id = '%s'",
mysql_real_escape_string($qty_credit),
mysql_real_escape_string($id));
Upvotes: 2
Reputation: 4244
SQL support arthmetic operations. So you can do the following:
"UPDATE avis_credits SET credits=credits + $qty_credit";
Upvotes: 2