mardi 31 octobre 2017

Global variable capture and math in PHP

I will keep this short in order to not take too much of your day, but I have been working on a certain project in PHP for some time now, and I am finally coming to a close on it. However, I seem to be having trouble grasping this concept of the global variable and how to successfully use it in the way I want and I am not quite sure why.

My program essentially does this:

  • Takes in a bunch of IDs and forms groups
  • Creates a page for them which has a report of all the information, allows for download once a button is pressed
  • Takes the member total current when the button is pressed, and translates that into the global variable which will now define another option on the page (member change since last report) by taking that and subtracting the total value from it

Some examples of my code starting from the definition start page

$GLOBALS['TheDifference']; //defines the variable for later use

On the actual viewing pages for the groups, keep in mind this statement is in a foreach, so it will repeat each time for each group

        $MemberDifference;
        if ($MemberDifference == 0) {
                $MemberDifference = $FailureMessage;
        }
//the above will be blank at first due to nothing being in it
        $pastmembers = $GLOBALS['TheDifference'];
        if ($pastmembers == 0) {
            $pastmembers = $TotalMembers;
        }
//this activates when the variable becomes filled
        $MemberDifference =  $pastmembers - $TotalMembers;

And finally, when the button on the report pages are clicked:

$GLOBALS['TheDifference'] = $TotalMembers;

The issue is essentially, my MemberDifference variables are always 0, and they do not seem to save as I hope they should (from the code directly above this, 0 turns into whatever that variable is, which will then end up subtracting the new TotalMembers from PastMembers).

I hope I explained this mostly, maybe even with too much information. PHP isnt my best language and while I feel I am missing something very simple, I cannot for the life of me wrap my head around it.

Thank you all in advance!

*Edit, the reason I need global variables is because this program essentially runs over many different pages, at least 5 in total, and the global variables are the only ones I really know as a way to do this. If there is a better way, feel free to let me know!




Aucun commentaire:

Enregistrer un commentaire