Jump to content

for each / array / loop ~ guidance needed :S


yourichi

Recommended Posts

 

Ok The basics of this function is to serve as a "tick"

(end goal to be called from a php file accessed as part of a chron job)

 

To update each row (user, who meet certain criteria) with the intention to increase or decrease by another stored variable within the user's row.

 

Please excuse the sloppy code, Im by no means even halfway good at php yet, I have a lot of bad habbits >.<

 

 

function populationtick()

/**Begin pull of all rows, then proceed to update each row for certain fields**/
{



$result = mysql_query("SELECT `id`,`towninc`,`maxpop`,`currentpop` FROM `users` WHERE `currentpop` < `maxpop`") or die (mysql_error()); 
$num = mysql_num_rows($result);
/** WHERE `currentpop` < `maxpop` **/
echo "$num rows found<br>";

list($id,$towninc,$maxpop,$currentpop) = mysql_fetch_row($result);


if($currentpop < $maxpop)
{
    $newpop = $currentpop + $towninc;
echo "$newpop will now be the new population";

    $updaterequired = "yes";
} else {
echo "$id town at max population";
$updaterequired = "no";
        exit;
       }

if ($newpop > $maxpop){
$newpop = $maxpop;
echo "over the max adjusting to max pop";
				  } 
if($updaterequired == "yes"){

mysql_query("UPDATE haypi.users SET currentpop ='$newpop'");
echo "update complete for $id done";
echo "new population is $newpop and the population inc was $towninc";
}




}
/**End Function **/

 

like i said its pretty sloppy, and I prolly should be using a more suitable array, at current this code (of course) will update all records based on the first record encountered (because i dont have the WHERE on the update query)

(failing to think of a suitable way to loop this through each row, to pull the new variables for each row an then process an update for each row.

 

Any help with this would be greatly appriciated!

Link to comment
Share on other sites

OK, I see a lot of things going on in that code and most of it is probably unnecessary. Can you explain in plain English what you are trying to accomplish? You don't need to run queries in loops, you can probably do all you need with just a couple of queries.

Link to comment
Share on other sites

ok simply put i want to run a tick based game

every 15minutes a tick will run and go through each players row in the DB and update the various relevant fields

 

Starting with a simple function first, once ive figured this out ill have the framework to create the rest.

 

This function is too read the players row, pull their max population, current population, and "income population per tick"

 

So i need it too read the number of population to add to each persons current population whilst ensuring they dont exceed the max.

 

Reason i store the income population as an individual variable for each user, as later on this figure will be possible to be different for each person based on the level of their city so to speak.

 

Hope that clarifys what im trying to achieve :)

 

Thanks

Link to comment
Share on other sites

OK, looking at your code, this is what I came up with. I basically see three "classes" of records:

 

1. Ones that are already at max population and should not be changed

2. Ones that are over max population and need to be reduced

3. Ones that are under max population and should be increased by 'towninc' UNLESS that would take them over the max population and in that case the population should be set at the max.

 

None of this is tested since I don't have your database so there may be some syntax/typo errors, but the logic should be sound

 

<?php

function populationtick()

/**Begin pull of all rows, then proceed to update each row for certain fields**/
{
    //Get list of towns already at max population
    $query  = "SELECT `id`, `maxpop` FROM `users` WHERE `currentpop` = `maxpop`";
    $result = mysql_query($query) or die (mysql_error());
    $atMaxPopAry = array()
    while($town = mysql_fetch_assoc($result))
    {
        $atMaxPopAry[$town['id']] = $town['maxpop'];
    }

    //Get list of towns over the max population
    $query  = "SELECT `id`, `maxpop` FROM `users` WHERE `currentpop` > `maxpop`";
    $result = mysql_query($query) or die (mysql_error());
    $overMaxPopAry = array()
    while($town = mysql_fetch_assoc($result))
    {
        $overMaxPopAry[] = [$town['id']] = $town['maxpop'];
    }
    //Reset current pop to max pop for those over max
    $query  = "UPDATE `users` SET `currentpop` = `maxpop` WHERE `currentpop` > `maxpop`";
    $result = mysql_query($query) or die (mysql_error());

    //Get list of towns under the max population
    $query  = "SELECT `id`, `currentpop`, `towninc`, `maxpop` FROM `users` WHERE `currentpop` < `maxpop`";
    $result = mysql_query($query) or die (mysql_error());
    $underMaxPopAry = array()
    while($town = mysql_fetch_assoc($result))
    {
        $underMaxPopAry[$town['id']] = min(($town['currentpop']+$town['towninc']),$town['maxpop']);
    }
    //Increate current pop to (current pop + towninc) or max pop, whichever is less
    $query  = "UPDATE `users` SET `currentpop` = IF(`currentpop`+`towninc`>`maxpop`, `maxpop`, `currentpop`+`towninc`) WHERE `currentpop` < `maxpop`";
    $result = mysql_query($query) or die (mysql_error());

    echo "The following towns were already at max population:<br>";
    echo "<ul>\n";
    foreach($atMaxPopAry as $townId => $pop)
    {
        "<li>{$townId} = {$pop}</li>\n";
    }
    echo "<ul>\n";
    echo "<br><br>\n";

    echo "The following towns were over max population and were reduced to the max population:<br>";
    echo "<ul>\n";
    foreach($overMaxPopAry as $townId => $pop)
    {
        "<li>{$townId} = {$pop}</li>\n";
    }
    echo "<ul>\n";
    echo "<br><br>\n";

    echo "The following towns under max population and were increased:<br>\n";
    echo "<ul>\n";
    foreach($underMaxPopAry as $townId => $pop)
    {
        "<li>{$townId} = {$pop}</li>\n";
    }
    echo "<ul>\n";

}
/**End Function **/

?>

Link to comment
Share on other sites

mm the logic does seem quite sound..

only 1 minor syntax error that i cant figure out is the second array

 

{
        $atMaxPopAry[$town['id']] = $town['maxpop'];
    }

    //Get list of towns over the max population
    $query  = "SELECT `id`, `maxpop` FROM `users` WHERE `currentpop` > `maxpop`";
    $result = mysql_query($query) or die (mysql_error());
    $overMaxPopAry = array()
    while($town = mysql_fetch_assoc($result))
    {
        $overMaxPopAry[] = [$town['id']] = $town['maxpop'];   <-- seems to make it unhappy ,
    }

Link to comment
Share on other sites

ah found it, needed to remove the [] = at the start of the array call

works perfectly, thank you very much!

 

Would you mind to explain a little exactly how the array works to achieve what i was after? as I will need to replicate various functions of similar nature.

Dont particularly like just copy an pasting code, I prefer to understand exactly what the code is supposed to be doing an how it reachs the results :)

otherwise I'll never improve lol

 

Thanks again!

Regards

Yourichi

Link to comment
Share on other sites

If you need to re-purpose this functionality you need to build a function that will take parameters and perform the necessary operations accordingly. If you need to do the same thing more than once, build it once so that it can meet the needs of the multiple scenarios you need. Otherwise your code become hard to maintain. For example, if you have copied the same logic multiple times and you later find a bug in a certain module you will have to try and remember where you used that same functionality.

 

Anyway, as to "how the array works" I'm not sure what you are asking. The real "work" in this code is done through the queries and I provided comments to explain what each query was doing. But, with respect to the arrays, they are simply a variable to hold the values from the queries using the record ID as the key and the populating of the value. Then later in the code it iterates through the respective arrays to display the values on the page. The one array that was built slightly different was the last one.

 

For the records where the population is less than the max,I first query for those records. Then when building the array I calculate what the new population will be by using the lower of the two values (currentpopulation + towninc) or (maxpopulation). Then, I run a query to set those new values using the same logic in the MySQL query. Now, that is the most efficient method that I could think of, but it does have a problem. Although I am using the same logic to calculate what the new values will be in PHP (for display purposes) and in MySQL for the actual update - those are two different processes. To be 100% accurate you should probably run three queries: one to get the values that need to be updated, a second to update the values, and a third to do a select on the records from the first query to get their updated values.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.