Here is the case first and then if necessary I'll post code:
The script
I have a PHP script with a for loop, that for loop will take 24
hours to be completed.
The problem
The page doesn't load because it waits until the for loop is
completed.
What I try to do
To show the page while the for loop is running
PD: Please don't suggest Google nor PHP Manual, both tried, nothing found.
Here some code:
for ($s = $getEnergy; $s < $maxEnergy; $s += $getEnergy + $sumEnergy2){
$prodToEnergySql = "UPDATE ".$planetSolar." SET energy = ".$s."";
$prodToEnergyResult = mysqli_query($db,$prodToEnergySql);
$solarSQL3 = "SELECT energy FROM ".$planetSolar."";
$solarResult3 = mysqli_query($db,$solarSQL3);
$solarRows3 = mysqli_fetch_array($solarResult3);
$solarEnergy = $solarRows3['energy'];
}
Note that $getEnergy is 0 and $maxEnergy 1.200, increment 0,14.
Alternative Code
while ($getEnergy < $maxEnergy ){
$prodToEnergySql = "UPDATE ".$planetSolar." SET energy = energy + ".$sumEnergy2."";
$prodToEnergyResult = mysqli_query($db,$prodToEnergySql);
$solarSQL3 = "SELECT energy FROM ".$planetSolar."";
$solarResult3 = mysqli_query($db,$solarSQL3);
$solarRows3 = mysqli_fetch_array($solarResult3);
$solarEnergy = $solarRows3['energy'];
}
Note: there are at least 8 variables needed to execute the script.
Related
I have an end point that I can send a GET request to and it returns a different result depending on the limit and offset.
https://example-foo-bar.com?l=100&o=0 // returns the first 100 items.
I want to create a for loop (or a Nested for loop I assume) that returns a 100 items at a time, adding the result to an array each time, until the end of the response. I have the code for sending the curl request and storing the result, just struggling on the batch processing part.
Something like:
https://example-foo-bar.com?l=100&o=0
https://example-foo-bar.com?l=100&o=99
https://example-foo-bar.com?l=100&o=199
https://example-foo-bar.com?l=100&o=218 // end of response ?
I also know how many result there are in total, stored as $count;
I ended up with something like this but it doesn't feel like the best practice:
function testLoop(){
$limit = 100;
$count = getCount();
$j = ceil($count/$limit);
for ($i = 0; $i < $j; $i++){
$offset = $i*100;
echo 'https://example-foo-bar?l='.$limit.'&o='.$offset.'';
}
}
testLoop();
I am not sure if I understand the question correctly. But are you looking for something like that?
$offset = 0;
$limit = 100;
$run = true;
$result_array = array();
while($run) {
$result_array = array_merge($result_array, json_decode(file_get_contents("https://example-foo-bar.com?l=".$limit."&o=".$offset),true));
$offset = $offset + $limit;
if($offset == {somenumber}) {
$run = false;
}
}
Then use a cron job to call the php file
Create table 'schedule' and store the data id, link_name,offset and status column
set cron to execute every 10 minutes and take First an entry (one) which status =0
pass param to testLoop($limit) to call function. It may entire link of only offset =0, offset =99, offset =199 like that
After completed to update status=1 in schedule table.
After 10 minute cron Call Step1.
Best way to use Cron for such type of batch process you can also use php-resque
I have a conundrum I'm struggling to crack.
I have a database with 719 entries that I'm running a script on, these entries are Characters in a game and is what they will be referenced as.
However my while loop stops at 360 every time...
See below:
$query = mysqli_query($con,"SELECT * FROM users ORDER BY entryID;");
// Start loopy loop
$runCount = 0;
$CharNum = 0;
echo "NumRows = ".mysqli_num_rows($query)."<br/>"; // Outputs: NumRows = 719
while ($row = mysqli_fetch_array($query)) {
echo "Character#: ".++$CharNum."<br/>"; // Outputs: Counter stops at 360??
$entryID = $row["entryID"];
$CharacterID = $row["characterID"];
$blue = $row["blue"];
$tsDatabaseID = $row["tsDatabaseID"];
$tsUniqueID = $row["tsUniqueID"];
$tsName = $row["tsName"];
if (...[tonnes of code here]
}
echo "Runcount = ".++$runCount."<br/>"; // Outputs: Another counter stops at 360??
}
echo [some report summary]
I have no idea how or why it is stopping, but it isn't crashing as the report summary is showing after the while finishes but it is too perfect to be 360 every time??
So fun story,
if (!mysqli_fetch_array($query)) {
Doesn't sanity check it like I thought to see if it's valid, but performs the fetch in a way it screws everything up. Perhaps someone can explain this who is better than I. But this was inside my if.
ok so this file runs every 15 minutes you get a income, farming and energy bonus at those stages but I don't want them to go over the $storagecap but they don't stop and they keep adding more and more food, gold, energy to your account and never stops.
What I am trying to do is add you income and then if your income goes over $storagecap put your gold to $storagecap but it doesnt work here is my code
<?php
include("functions.php");
connect();
include("user_stats.php");
?>
<?php
if(isset($_SESSION['uid'])){
include("safe.php");
include("storagecap.php");?>
<?php
$get_users = mysql_query("SELECT * FROM `stats`") or die(mysql_error());
while($user = mysql_fetch_assoc($get_users)) {
//Get
$gold = $user["gold"];
$food = $user["food"];
$energy = $user["energy"];
//Increment
$gold += $user["income"];
$food += $user["farming"];
$energy += 5;
//Verify and correct
if($energy > 100)
$energy = 100;
if($gold > $storagecap)
$gold = $storagecap;
if($food > $storagecap)
$food = $storagecap;
//Submit
$update = mysql_query("UPDATE `stats` SET
`gold`= '".$gold."',
`food`= '".$food."',
`energy`= '".$energy."' WHERE `id`='".$user['id']."'") or die(mysql_error());
}
?>
Seems to me that you are having some syntax problems in your overflow checks.
for one, even if this worked they would have an amount above cap until the next 15 minute round.
For example, let say you had 99 energy, and it added 5, you would now have 104. But the cap check would still have the old values, i.e. 99, and would do nothing.
Also
`gold`=`gold` '$storagecap'
is not correct, you need to use
`gold`= '".$storagecap."'
But to fix the 15 minute delay the best method would be this:
<?php
include("functions.php");
include("storagecap.php");
connect();
$get_users = mysql_query("SELECT * FROM `stats`") or die(mysql_error());
while($user = mysql_fetch_assoc($get_users)) {
//Get
$gold = $user["gold"];
$food = $user["food"];
$energy = $user["energy"];
//Increment
$gold += $user["income"];
$food += $user["farming"];
$energy += 5;
//Verify and correct
if($energy > 100)
$energy = 100;
if($gold > $storagecap)
$gold = $storagecap;
if($food > $storagecap)
$food = $storagecap;
//Submit
$update = mysql_query("UPDATE `stats` SET
`gold`= '".$gold."',
`food`= '".$food."',
`energy`= '".$energy."' WHERE `id`='".$user['id']."'") or die(mysql_error());
}
?>
Please note I have not tested this code, treat it as a rough example
EDIT:
Just another note, if this query is run, returning energy of, say 99, and it have to fix this to 100, and in another query running at the same time, some energy I used. This might cause this used energy to be "given back". Sorry, I can't explain it better =P Look into MySQL transactions.
I have a php file that I run via cron. For testing I've set it to run every hour, but normally it will run once a day. What I want is to make it so that if the player has the autotechrefinery field set to 1, then they should have their population pulled from the table, how much money, research supplies, and technology they have.
From there, what I want is to deduct 500 researchsupplies, add 50 technology, and deduct 10% of population from money. All of this seems to be working when I run the file manually, but when I let it run automatically via cron, there is something that isn't working that as a result it sets technology to 50, researchsupplies to -500 and money to 0.
$refCheck = mysql_query("SELECT * FROM players WHERE autotechrefinery='1'");
while($rC = mysql_fetch_array($refCheck)) {
$nation = $rC['nation'];
$pop = $rC['population'];
$rsupplies = $rC['researchsupplies'];
$cash = $rC['money'];
$tech = $rC['technology'];
$newtech = $tech+50;
$newmoney = $cash-($pop*.1);
$newsupplies = $rsupplies-500;
mysql_query("UPDATE players SET money='$newmoney', technology='$newtech', researchsupplies='$newsupplies', techbought='1' WHERE autotechrefinery='1'"); }
The bug in your code is: the UPDATE will always update all entries. So all entries get the value assigned of the last pass of your loop.
To fix the code you need some ID to identify the row and use it in the update:
$refCheck = mysql_query("SELECT * FROM players WHERE autotechrefinery='1'");
while($rC = mysql_fetch_array($refCheck)) {
$ID = $rC['id'];
$nation = $rC['nation'];
$pop = $rC['population'];
$rsupplies = $rC['researchsupplies'];
$cash = $rC['money'];
$tech = $rC['technology'];
$newtech = $tech+50;
$newmoney = $cash-($pop*.1);
$newsupplies = $rsupplies-500;
mysql_query("UPDATE players SET money='$newmoney', technology='$newtech', researchsupplies='$newsupplies', techbought='1' WHERE id="$ID');
}
You didn't ask for improvements but you could achieve the same result with one SQL statement:
UPDATE players set money=money - population * .1, technology = technology + 50, researchsupplies = researchsupplies - 500;
I would like to have a function that would return the best a multidimension array of Associative arrays. I separated the whole output in three sections to make it read better.
What is the best way to parse such text? Where the output would be like
$output = array
(
"18"=>array(
"type"=>"backup",
"name"=>"PLC",
"Description"=>"offline db",
"state"=>"Executing",
"Start Time"=>"05/16/2012 10:55:45.240272"
),
"17"=>array(
"type"=>"restore",
"name"=>"TYNDALE",
"Description"=>"db",
"state"=>"Executing",
"Start Time"=>"05/16/2012 10:49:53.340805"
),
"15"=>array(
"type"=>"restore",
"name"=>"carinya",
"Description"=>"automatic incremental db",
"state"=>"Executing",
"Start Time"=>"05/16/2012 10:48:21.423945"
)
);
Section One + Two + Three are returned from linux command db2 list utilities show detail. So it would be an array of lines in php.
Section One
ID = 18
Type = BACKUP
Database Name = PLC
Partition Number = 0
Description = offline db
Start Time = 05/16/2012 10:55:45.240272
State = Executing
Invocation Type = User
Throttling:
Priority = Unthrottled
Progress Monitoring:
Estimated Percentage Complete = 0
Total Work = 3320093100 bytes
Completed Work = 255380 bytes
Start Time = 05/16/2012 10:55:45.240303
Section two
ID = 17
Type = RESTORE
Database Name = TYNDALE
Partition Number = 0
Description = db
Start Time = 05/16/2012 10:49:53.340805
State = Executing
Invocation Type = User
Progress Monitoring:
Completed Work = 117444608 bytes
Start Time = 05/16/2012 10:49:53.340819
Section Three
ID = 15
Type = RESTORE
Database Name = CARINYA
Partition Number = 0
Description = automatic incremental db
Start Time = 05/16/2012 10:48:21.423945
State = Executing
Invocation Type = User
Progress Monitoring:
Phase Number = 1
Total Work = 16781312 bytes
Completed Work = 16781312 bytes
Start Time = 05/16/2012 10:48:21.423954
Phase Number [Current] = 2
Description = 20120513023104
Completed Work = 272633856 bytes
Start Time = 05/16/2012 10:48:23.502822
Phase Number = 3
Description = 20120514021520
Completed Work = 0 bytes
Start Time = Not Started
So the code I use is
function db2listutilities(){
global $db2Path;
$status = array();
$ProgressMonitoring=false;
$cmd = $db2Path . "db2 list utilities show detail" ;
unset($output);
exec($cmd, $output);
foreach ($output as $line){
if( strpos($line,'Progress Monitoring:') !== false ){
$ProgressMonitoring=true;
}
$tmp_array=explode("=", $line);
if (count($tmp_array)>1){
switch (trim($tmp_array[0])) {
case 'ID':
$id=$tmp_array[1];
$ProgressMonitoring=false;
break;
case 'Type':
$status[$id]['Type']=$tmp_array[1];
break;
case 'Database Name':
$status[$id]['Database Name']=$tmp_array[1];
break;
case 'Description':
if (!$ProgressMonitoring) {$status[$id]['Description']=$tmp_array[1];}
break;
case 'Start Time':
if (!$ProgressMonitoring) {$status[$id]['Start Time']=$tmp_array[1];}
break;
case 'State':
$status[$id]['State']=$tmp_array[1];
break;
}
}
}
$return=array();
foreach ($status as $st) {
$return[] = $st['Database Name']." - ".strtolower($st['Type'])." - ".$st['State']." - ".date("H:i",strtotime($st['Start Time']))."<BR>";
}
return implode("",$return);
}