1

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?

2 Answers 2

2

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));
Sign up to request clarification or add additional context in comments.

1 Comment

Thank you there is only one row per database so I don't really need to be concerned about the id of the row as no others info or rows set in the database. Your assistance greatly appreciated
2

SQL support arthmetic operations. So you can do the following:

 "UPDATE avis_credits SET credits=credits + $qty_credit";

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.