Bradley Hodges Bradley Hodges - 2 years ago 132
SQL Question

PHP - Subtracting a number from mysql table values

This may seem like a bit of an odd request, but it's important that I get this working. It's for a game i'm making. So basically, my users have their own accounts on my website. I have different plans that they can select and each plan costs a different amount every month.

What I want to do is have 4 seperate PHP crons that automatically subtract a certain amount from their accounts each month based on the plan they have selected. For example, if a user has the "Ultimate" plan, and currently has $1,049.99 in their account, I want it to subtract 49.99 from the "balance" row in the database, and then update the table to

(as it has subtracted the plan amount).

At registration, the database is loaded with the value "chargeday" which is basically the day of the month that the user registered. I want the cron to run every day (which I know how to do) and only run this code if the current day equals the chargeday listed on the database. (I've been running this code with the
if ($chargeday == date("d")) {
lines removed.

I've tried the following but I can't get it to work the way I want:

$servername = "localhost";
$username = "myusername";
$password = "mypassword";
$dbname = "advenaio_myaccount";

$chargeday = date("d");
if ($chargeday == date("d")) {

$conn = new mysqli($servername, $username, $password, $dbname);
// Check connection
if ($conn->connect_error) {
die("Connection failed: " . $conn->connect_error);

$sql = "SELECT email, plan, balance FROM advaccounts WHERE plan='ultimate'";
$result = $conn->query($sql);

$ultimateplan = "49.99";
$currentbalance = $row['balance'];
$newbalance = $currentbalance-$ultimateplan;

if ($result->num_rows > 0) {
// output data of each row
while($row = $result->fetch_assoc()) {
echo "plan: " . $row["plan"]. "<br>balance: " . $row['balance'] . "<br>new balance: " . $newbalance . "<br>email address: " . $row['email'] . "<br><br> ";
} else {
echo "0 results";

$sql = "UPDATE advaccounts SET balance=$newbalance WHERE plan='ultimate'";

if ($conn->query($sql) === TRUE) {
echo "Record updated successfully";
} else {
echo "Error updating record: " . $conn->error;


I'm sorry if my question doesn't make sense, I just really need this to work and I'm sort of desperate for it to work. Here is the structure of the database:

id_user | name | email | domain | username | password | plan | balance | joindate | chargeday | substatus | cic

Answer Source

you can use below sql to update the balance directly using one sql. No need to write php logic.

$sql = "UPDATE advaccounts SET balance=balance-49.99 WHERE plan='ultimate' and chargeday = '" . date('d'). "'";  
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download