Add data to secondary table

Read what you’ve written. The first query is not required, because all you need is the user id and the value to add to the wallet column. Your code reads the balance (wallet), adds the new wallet to it, then runs a query that adds it on again.

All you need is the second query. Obviously changed to use prepared statements with parameters for the values.

Much thanks again, I see what you mean.

So, this hasn’t worked, but something like this?

$newValue = wallet;
$sql = "UPDATE users SET wallet = wallet + $newValue WHERE user_id = 'user_id'";

Stop guessing. Write down in words what you want to achieve and then convert that to code.

Thanks for your message.
Here are the words: instead of the Form field entered amount replacing the displayed amount in the ‘wallet’ column, the entered amount adds to (or subtracts) whatever is in the ‘wallet’ column.

I don’t know how to convert that to code, but I believe what I’ve posted in close.

Any suggested improvement on that code, is appreciated.

That sounds correct. But your code is adding the user’s wallet to their wallet, so basically doubling what they have.

the entered amount adds to (or subtracts) whatever is in the ‘wallet’ column.

So let’s break this down.

the entered amount

Right, so we need a value from $_POST
Let’s store it somewhere

$addedBalance = $_POST['wallet'];

adds to (or subtracts)

So we need an UPDATE query with a + in it somewhere

$addedBalance = $_POST['wallet'];
$sql = 'UPDATE ??? SET ??? = ??? + :addedBalance';

whatever is in the ‘wallet’ column.

Ah, so we need to take what is in the wallet column, and add the amount from the form.

$addedBalance = $_POST['wallet'];
$sql = 'UPDATE ??? SET wallet = wallet + :addedBalance';

Now, from that sentence we still don’t know which table to update, and which restrictions apply. Maybe you could finish that? :slight_smile:

I think that’s just because @ChrisjChrisj uses the term “wallet” for the transaction amount entered in the html form (in the first post, that’s the html input tag name and I believe it follows through into the variable name $wallet), and the running balance column in the user table. It is confusing, and should be changed before too much code uses it, IMO.

It is close, once you put the variables into the query or use a prepared statement. You have a variable for your new amount to be added, you just haven’t used a variable for the user-id, you’ve used a quoted string.

Thanks again for the replies.

I have tried this:

$addedBalance = $_POST['wallet'];
$sql = "UPDATE users SET wallet = wallet + $addedBalance where user_id ='id'";

and I have tried:

$newValue = wallet;
$sql = "UPDATE users SET wallet = wallet + $newValue WHERE user_id = 'id'";

but each time I submit a new number into the Form field and ‘submit’

that number appears in the ‘wallet’ column of the db.
Nothing gets added to anything else.

Any additional suggestions are welcomed.

You’ve got an actual user that’s user_id has the value “id” and not any number?

Don’t you get a syntax error on this line? And what @chorn said, you need to use the variable that contains your user-id, not the string text “id”.

Can you clarify? Which of the two tables - the transactions, or the users - does the number appear in?

Thanks again for the replies.
I’m not clear on this question: “You’ve got an actual user that’s user_id has the value “id” and not any number?”, but I can tell you that the ‘id’ column in the ‘user’ db displays a number. It’s structure shows.
id[Primary] int(11) NULL= No Default=None AUTO_INCREMENT

The ‘wallet’ structure shows:
wallet(grey key) varchar(200) utf8_general_ci NULL=No Default=0
Here is the php file lines 1 thru 165. I’ve added $newValue = wallet; etc on line 148
Regarding which table does the number appear in, it is ‘user’ table.

<?php
if (empty($_POST['user_id']) || !IS_LOGGED) {
    exit("Undefined Dolphin.");
}

$is_owner = false;
if ($_POST['user_id'] == $user->id || PT_IsAdmin()) {
    $is_owner = true;
}
if ($first == 'change_price') {
    if (!empty($_POST['subscriber_price']) && (!is_numeric($_POST['subscriber_price']) || $_POST['subscriber_price'] < 0)) {
        $errors[] = $error_icon . $lang->please_check_details;
    }
    if (empty($errors)) {
        $update_data = array();
        $update_data['subscriber_price'] = 0;
        if ($pt->config->payed_subscribers == 'on' && !empty($_POST['subscriber_price']) && is_numeric($_POST['subscriber_price']) && $_POST['subscriber_price'] > 0) {
            $update_data['subscriber_price'] = PT_Secure($_POST['subscriber_price']);
        }
        if ($is_owner == true) {
            $update = $db->where('id', PT_Secure($_POST['user_id']))->update(T_USERS, $update_data);
        }
        $data = array(
                    'status' => 200,
                    'message' => $success_icon . $lang->setting_updated
                );
    }
}

if ($first == 'general') {
    if (empty($_POST['username']) OR empty($_POST['email'])) {
        $errors[] = $error_icon . $lang->please_check_details;
    }

    else {
        $user_data = PT_UserData($_POST['user_id']);
        if (!empty($user_data->id)) {
            if ($_POST['email'] != $user_data->email) {
                if (PT_UserEmailExists($_POST['email'])) {
                    $errors[] = $error_icon . $lang->email_exists;
                }
            }
            if ($_POST['username'] != $user_data->username) {
                $is_exist = PT_UsernameExists($_POST['username']);
                if ($is_exist) {
                    $errors[] = $error_icon . $lang->username_is_taken;
                }
            }
            if (in_array($_POST['username'], $pt->site_pages)) {
                $errors[] = $error_icon . $lang->username_invalid_characters;
            }
            if (!filter_var($_POST['email'], FILTER_VALIDATE_EMAIL)) {
                $errors[] = $error_icon . $lang->email_invalid_characters;
            }
            if (!empty($_POST['donation_paypal_email'])) {
                if (!filter_var($_POST['donation_paypal_email'], FILTER_VALIDATE_EMAIL)) {
                    $errors[] = $error_icon . $lang->email_invalid_characters;
                }
            }

            if (strlen($_POST['username']) < 4 || strlen($_POST['username']) > 32) {
                $errors[] = $error_icon . $lang->username_characters_length;
            }
            if (!preg_match('/^[\w]+$/', $_POST['username'])) {
                $errors[] = $error_icon . $lang->username_invalid_characters;
            }
            $active = $user_data->active;
            if (!empty($_POST['activation']) && PT_IsAdmin()) {
                if ($_POST['activation'] == '1') {
                    $active = 1;
                } else {
                    $active = 2;
                }
                if ($active == $user_data->active) {
                    $active = $user_data->active;
                }
            }
            $type = $user_data->admin;
            if (!empty($_POST['type']) && PT_IsAdmin()) {
                if ($_POST['type'] == '2') {
                    $type = 1;
                }

                else if ($_POST['type'] == '1') {
                    $type = 0;
                }
                if ($type == $user_data->admin) {
                    $type = $user_data->admin;
                }
            }

            $is_pro = $user_data->is_pro;
            if (isset($_POST['is_pro']) && PT_IsAdmin()) {
                if ($_POST['is_pro'] == 1) {
                    $is_pro = 1;
                }

                else if ($_POST['is_pro'] == 0) {
                    $is_pro = 0;
                }
            }

            $gender       = 'male';
            $gender_array = array(
                'male',
                'female'
            );
            if (!empty($_POST['gender'])) {
                if (in_array($_POST['gender'], $gender_array)) {
                    $gender = $_POST['gender'];
                }
            }

            $field_data         = array();
            if (!empty($_POST['cf'])) {
                $fields         = $db->where('placement','general')->get(T_FIELDS);
                foreach ($fields as $key => $field) {
                    $field_id   = $field->id;
                    $field->fid = "fid_$field_id";
                    $name       = $field->fid;
                    if (isset($_POST[$name])) {
                        if (mb_strlen($_POST[$name]) > $field->length) {
                            $errors[] = $error_icon . $field->name . ' field max characters is ' . $field->length;
                        }
                        else{
                            $field_data[] = array(
                                $name => $_POST[$name]
                            );
                        }
                    }
                }
            }
            $age = $user_data->age;
            $age_changed = $user_data->age_changed;
            if (($_POST['age'] >= 0 && $_POST['age'] < 100) && $age != $_POST['age']) {
                if (!PT_IsAdmin()) {
                    if ($user_data->age_changed > 1) {
                        $errors[] = $error_icon . $lang->not_allowed_change_age;
                    } else {
                        $age = PT_Secure($_POST['age']);
                        $age_changed = $user_data->age_changed + 1;
                    }
                } else {
                    $age = PT_Secure($_POST['age']);
                }
            }

            $newValue = wallet;
	$sql = "UPDATE users SET wallet = wallet + $newValue WHERE user_id = 'id'";

            if (empty($errors)) {
                $update_data = array(
                    'username' => PT_Secure($_POST['username']),
                    //'wallet' => PT_Secure($_POST['wallet']),
                    'wallet' => $newValue,
                    'email' => PT_Secure($_POST['email']),
                    'gender' => PT_Secure($gender),
                    'country_id' => PT_Secure($_POST['country']),
                    'active' => PT_Secure($active),
                    'admin' => PT_Secure($type),
                    'is_pro' => $is_pro,
                    'age' => $age,
                    'age_changed' => $age_changed,
                    'donation_paypal_email' => PT_Secure($_POST['donation_paypal_email'])
                );

any additional suggestions are appreciated.

So your SQL would do nothing (but should at least raise an error) because your condition user_id = 'id' never matches, as long as you are not using the actual user_id number.

but I can tell you that the ‘id’ column in the ‘user’ db

So you got no table “users”? And there’s not even a column “user_id”, so what sense makes your condition?

Thanks for your reply.

Can you make a suggestion as to what the condition should be?

Also, sorry, I meant to say the ‘users’ table (not ‘user’ table).

I look forward to any additional suggestions.

You see here in this code that you’ve added:

$newValue = wallet;
$sql = "UPDATE users SET wallet = wallet + $newValue WHERE user_id = 'id'";

you create a variable called $newValue. You can tell it’s a variable because it starts with a dollar sign, which is how PHP - all the PHP code you’ve already got - names variables. You then try to assign the value of wallet to it - but that isn’t a variable, because it doesn’t start with a dollar-sign. It’s not a string either, because it hasn’t got quotation marks - single or double - around it. So PHP assumes it’s a constant, but if you haven’t defined it as such, you should be getting an error message on this line if you have error-reporting enabled, like I said before. If you don’t have it enabled, you should enable it on your development system while you’re developing new code, especially if you’re unfamiliar with the language.

So, where does your value for wallet come from? If it’s a form input, then you can see how you get all the other form input values, and use the same method to get the wallet value from the form. You must have that correct somewhere, because you said it’s being written into the transactions table correctly at one point.

On the second line of code, you can see how you use a variable name inside a query string, because you use $newValue correctly - or you would, if it had a value - but it will have, once you’ve corrected the error on the first line. So, you can see what the difference is between a variable inside a query, and a fixed string. You are using a fixed string of id for your user-id, and you need to use the correct variable instead.

The other issue, of course, is that while you create a query string, you don’t actually execute the query anywhere. So once you’ve corrected the error in line 1 of the code I’ve highlighted, and corrected the incorrect WHERE clause in the second line, you have to then execute the query to make it alter the database.

2 Likes

Thanks again for your reply. I have this now, without success:

         $id = $_POST['user_id'];
         $newValue = $_POST['wallet'];
      	 $sql = "UPDATE users SET wallet = wallet + $newValue WHERE user_id = '$id'";
         $sql->execute();

            if (empty($errors)) {
                $update_data = array(
                  'wallet' => PT_Secure($_POST['wallet']),
etc....

any additional help is welcomed

This bit

$sql = "UPDATE users SET wallet = wallet + $newValue WHERE user_id = '$id'";
$sql->execute();

is not correct - I’m surprised you don’t get an error message when you try. You need to execute the query against your database connection object, not against the query string itself. Looking at some of your earlier posts in here, that might be $db, but you should check that.

If that doesn’t help

again doesn’t tell us anything. Does it have the correct values in those two variables when you var_dump them? Do you get any errors after you execute the query? If you execute the same query with made-up values from phpmyadmin does it work, or do you get errors?

Thanks for your reply.
Regarding “without success”, it means it is the same result, the number entered into the html Form just replaces the number displayed in the users > wallet column.
adding:

$sql->execute();
or
$sql->execute();
or 
var_dump($newValue);

just prevents the html Form from submitting. No errors.

Regarding “made up values”, if you mean something like this:

$sql = "UPDATE users SET wallet = wallet + 3 WHERE user_id = '$id'";

same result: what is entered into the html Form is what is stored there after submit.

Any additional ideas/suggestions is appreciated.

As I said before, the above line will not work because $sql is your query string, not your database connection object. Look at your earlier posts, post #3 shows you what your database connection object (in that code) is set to I think.

Well, you must have some other code that’s doing that, because the query you’ve shown recently won’t be doing it as it’s not executing.

No, I meant make some values up and run the query from phpmyadmin and see why it’s not working. Nothing to do with your html form. Look at the query above, which bit of that won’t be an acceptable value when you run it in phpmyadmin?

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.