setting a limit to a income every 15 minutes error - php

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.

Related

pHp Issue: "Waiting for localhost": Maybe infinite loop issue?

I am currently working on an elo based matchmaking system. Basically, I have a database where there are a bunch of users, each having their respective ratings.
Brief explanation of code, it chooses one user at random, and chooses another user if the second user is within +-100 difference-elo of the first user (so grandmasters don't play with bronze players). If there is no one within 100 elo, the difference-elo increments by 50 and checks again.
Problem: I created a test user that is 100 elo more than the other users to test the matchmaking system. The program works except for when the first selected player is my test user. The page never loads and it is stuck on "Waiting for localhost". I assumed this meant one of my while loops was going on infinitely, but after spending sometime editing them and trying to figure out why they might be going on infinitely, the error still persists.
<?php
include('mysql.php');
include('functions.php');
$result2 = executeQuery("SELECT * FROM images ORDER BY score DESC");
function executeQuery($query2){
$connect = mysqli_connect("localhost", "root", "password","database");
$result2 = mysqli_query($connect, $query2);
return $result2;
}
// Get random
$query="SELECT * FROM images ORDER BY RAND() LIMIT 0,1";
$result = #mysqli_query($connection, $query);
//Put random in images array
while($row = mysqli_fetch_object($result)) {
$images[] = (object) $row;
}
//Get elo of random
$elo1 = $images[0]->score;
--------------------------
//Point of Interest Below
--------------------------
//Sort database by DESC. Then go through entire database. If current row's elo is with +- difference (which right now is 100) of elo1's rating, ($elo1-100 < x < $elo1+100), then put into new array with all matchups.
//Get length of array, if length is 0 (meaning no match ups were found), increase difference by 50 and try again.
$potentialMatchup = [];
$diff = 100;
$arrayLength = count($potentialMatchup);
while ($arrayLength == 0){
$diff += 50;
while($row2 = mysqli_fetch_object($result2)){
if(($row2->score > $elo1-$diff) && ($row2->score < $elo1+$diff)){
$potentialMatchup[] = (object) $row2;
}
}
$arrayLength = count($potentialMatchup);
}
-------------------------------
//Get random index between 0 and length of array.
$randomNumber = rand(0, $arrayLength-1);
//Put match up into images array
$images[1] = (object) $potentialMatchup[$randomNumber];
//Get names of images
$nameLeft = $images[0]->filename;
$nameRight = $images[1]->filename;
//If same person, pick another random
while($nameLeft == $nameRight){
$randomNumber = rand(0, $arrayLength-1);
$images[1] = (object) $potentialMatchup[$randomNumber];
$nameRight = $images[1]->filename;
}
// Close the connection
mysqli_close($connection);
$leftName = str_replace("_", " ", $images[0]->filename);
$rightName = str_replace("_", " ", $images[1]->filename);
?>

How to load a php page with a 24 hours script running?

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.

add multiple leading zeros in odometer

I was tried reward polling using odometer, now I want my number polling is lead by zero,
1,239,387 be 001,239,387,
it start from 123456789. When odometer is running, result without 00, just 1,239,387.
this code I tried with concat or add prefix to add lead zero. But if lead with > 0 it display
<?php
$query="SELECT
CONCAT('00',MBR_ID) AS MBR_ID,
NAME,
RWD_DESC
FROM RTL.RWD_POLL RWD
JOIN RTL.RWD_HEAD HED ON RWD.RWD_HEAD_NBR = HED.RWD_HEAD_NBR
WHERE HED.ACT_F = 1 AND RWD.DEL_NBR = 0
ORDER BY RWD_POLL_NBR DESC";
$result = mysql_query($query);
$row = mysql_fetch_array($result);
$MbrN = $row['MBR_ID'];
$names = $row['NAME'];
$reward = $row['RWD_DESC'];
//$NoUndian = sprintf('%02d',$MbrN);
?>
<script>
setTimeout(function(){
$('.odometer').html(<?php echo $NoUndian; ?> );
}, 1000);
</script>
The result still 1,239,387 without zero.

issue with php number_format()

I'm having an issue with number_format. When $val is over 1,000 in value, the $update will only SET a value of 1. If it is less than 1,00 in value, it will SET the correct value.
pmV is DECIMAL, 7,2.
I'm sure that I have just stared at this for too long and am missing something. What am I doing wrong? Please school me! ;)
// Set variables for received data
$id = strval($_GET['id']); // value is 1
$k = strval($_GET['k']); // value is 1
$dwt = strval($_GET['dwt']); // value is 25
$spot = "." . strval($_GET['spot']); // value is .70
//Query the database based on the variables received and 'echo' the results back
$sql="SELECT * FROM metals WHERE id = '".$id."'";
$result = mysqli_query($con,$sql);
while($row = mysqli_fetch_array($result)) {
if ($id == 1){ // If we are calculating Gold, then add Karat into the calculation
$num = ((($row['value']/20)*$k)*$dwt)*$spot; //$row['value']=1200.01
}
else { // If not, then don't
$num = (($row['value']/20)*$dwt)*$spot;
}
$val = number_format($num,2,'.',',');
echo $val; // Send the value back to page --> Sending correct value - 1,050.01
// Update the DB with the calculated PM amount
$update="UPDATE totals SET pmV = $val WHERE id='1'";
$result2 = mysqli_query($con,$update); // UPDATES value of pmV to '1' instead of 1,050.01
// Get the Diamond Value from the DB and Update the Total calculation
$select="SELECT dV FROM totals WHERE id='1'";
$result3 = mysqli_query($con,$select);
while($dv = mysqli_fetch_array($result3)) {
$val2 = $dv['dV']+$val;
$sql4 = "UPDATE totals SET total = $val2 WHERE id='1'";
$result4 = mysqli_query($con,$sql4);
};
};
mysqli_close($con);
1,050.01 is not a valid number. It's a formatted string. So when you try to treat it like a number, things break.
To round a number to teo decimal places, try this:
$val = floor($num*100)/100;

Rating System Won't Average Correctly

I have a rating system that uses the following equation to generate the rating average:
((Old Rating*Old Times Amount)+New Rating)/New Rating amount
However, if the current rating is 3, and it's been rated once, when I rate it three, it says the new rating is 2.5
What is the error here? Here's the full code.
<?php
session_start();
include("lib/db.php");
$db = new DBConnect;
if(isset($_POST['rating']) && is_numeric($_POST['rating']) && is_numeric($_POST['story']))
{
if($_POST['rating'] > 5 || $_POST['rating'] < 1){die("INVALID RATING");}
$rating = mysql_real_escape_string($_POST['rating']);
$story = mysql_real_escape_string($_POST['story']);
$c = $db->query("SELECT * FROM cdb_stories WHERE id=$story");
$c = mysql_fetch_array($c);
$u_name = mysql_real_escape_string($_SESSION['logged_in']);
$uid = $db->query("SELECT id FROM cdb_users WHERE username='{$u_name}'");
if(mysql_num_rows($uid) < 1){die("NOT LOGGED IN");}
$uid = mysql_fetch_array($uid);
$ratingd = $db->query("SELECT * FROM cdb_ratings WHERE userid='{$uid['id']}'");
if(mysql_num_rows($ratingd) > 0)
{
$ratingd = mysql_fetch_array($ratingd);
$new_rate = (($c['rating']*$c['rating_amt'])-$ratingd['rating']+$rating)/$c['rating_amt'];
$db->query("UPDATE cdb_stories SET rating={$new_rate} WHERE id={$story}");
$db->query("UPDATE cdb_ratings SET rating={$rating} WHERE userid='{$uid['id']}'");
die();
}
$new_num = $c['rating_amt']+1;
$new_rate = (($c['rating']*$c['rating_amt'])+$rating)/$new_num;
$db->query("UPDATE cdb_stories SET rating_amt={$new_num}, rating={$new_rate} WHERE id={$story}");
$db->query("INSERT INTO cdb_ratings VALUES({$uid['id']},{$rating},{$story})");
}
else
{
die("INVALID FIELDS");
}
?>
((Rating * Times) + New) / (Times + 1)
For your values:
((3 * 1) + 3) / (1 + 1)
= ( 3 + 3) / 2
= 6 / 2
= 3
So the procedure looks mathematically correct.
I suggest you put the calculation into a function of it's own with parameters, so you don't get irritated so much by the rest of the code you have in that batch. This will make it easier to debug for you:
function new_rate($rating, $times, $new)
{
return (($rating * $times) + $new) / ($times + 1);
}
You can then use that more easily within your code. Additionally if something else is the cause of the error, you can simply find out by testing the bare function. If it acts correct, you know that the error is placed somewhere else.
Hope this helps.

Categories