How to Put an IF statement inside a Loop - php

OK so I have this loop, I want to change the value if the loop lands on a certain value. for example in the code below, $p will equal 15 for Tier2. but when running the script nothing happens, it just runs as normal and ignores my if statement.
$get_sponsor = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT sponsor FROM ap_members WHERE id=$affiliate_id"));
$sponsor = $get_sponsor['sponsor'];
for ($loop = 2 ; $loop < $levels; $loop++){
//CHECK FOR AVAILABLE SPONSOR
if($sponsor!='0'){
//GET LEVEL PERCENTAGE
$gp = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM ap_other_commissions WHERE id=1"));
$p = $gp['tier'.$loop.''];
if($p == 15){ // changes for custom override
$sc = $tier2_com / 100;
} else {
$sc = $p / 100;
}
$se = $sale_amount * $sc;

//GET LEVEL PERCENTAGE
$gp = mysqli_fetch_assoc(mysqli_query($mysqli, "SELECT * FROM ap_other_commissions WHERE id=1"));
$p = $gp['tier'.$loop.''];
if($loop == 2){ // changes for custom override
$p = $tier2_com;
$sc = $tier2_com / 100;
} else {
$sc = $p / 100;
}
$se = $sale_amount * $sc;
I released that i was missing the $p in the if statement to give to update it correctly in the database. all is working now.. thanks for the suggestions guys.

Related

Compare array values to calculate % in PHP?

So the goal is to be able to create a dynamic value for my progress bar based on dynamic variables from the database. Below is a pseudo code for what i am looking for if its possible:
//League rank names
['bronze_V','bronze_IV','bronze_III','bronze_II','bronze_I'];
Lets say i start at bronze_IV to bronze_II i need to calculate that to 100?
and then i need to store that value is that possible to be dynamic?
are you trying something like this,
$data = ['bronze_V','bronze_IV','bronze_III','bronze_II','bronze_I'];
$start = $end = 0;
while($element = current($data)) {
if ($element == 'bronze_IV') $start = key($data);
if ($element == 'bronze_I') $end = key($data);
next($data);
}
$percentage = ( (($end-$start) + 1) / count($data) ) * 100;
var_dump($percentage); //float(80)
example with multiple tiers,
#note : badge count for each tier has to be 5 for this to work,
#if you change the count change change the value inside the loop
$data = array(
['silver_V','silver_IV','silver_III','silver_II','silver_I'],
['bronze_V','bronze_IV','bronze_III','bronze_II','bronze_I']
);
$start = $end = 0;
$start_badge = 'silver_V';
$end_badge = 'bronze_II';
//loop through tiers
foreach ($data as $key => $tier) {
//loop through badges
while($badge = current($tier)){
//position of the start badge
if ($badge == $start_badge) $start = ($key * 5) + key($tier)+1; //see note
//position of the end badge
if ($badge == $end_badge) $end = ($key * 5) + key($tier)+1; //see note
next($tier);
}
}
//count badges
$badges_count = (count($data, COUNT_RECURSIVE) - count($data));
//calculate percentage
$percentage = ( (($end-$start) + 1) / $badges_count ) * 100;
var_dump($percentage); //float(90)

leveling up PHP algorithm

I want some algorithm to make a PHP level up system I already made a system to level up people but what if people gained a huge amount of exp so they need to level up multiple times example of my code:
if(isset($_POST['id']) && isset($_POST['amount'])) {
$amount = $_POST['amount'];
$user = $_POST['id'];
$exp;$etnl;$newExp;$level;
`//select exp and etnl from DB
$result = DB::getInstance() ->query("SELECT exp,etnl,level FROM exp WHERE id = $user");
$result->setFetchMode(PDO::FETCH_ASSOC);
$row = $result->fetch();
$exp = $row['exp'];
$etnl = $row['etnl'];
$level = $row['level']
//c where to level up user or to add exp to his ep bar
if($amount + $exp > $etnl) {
$etnl = $etnl * 2;
$leftOvers = ($amount + $exp) - $etnl;
$newExp = $leftOvers;
$level = $level + 1;`
$result = DB::getInstance()->prepare("UPDATE exp SET exp=?,level=?,etnl=? WHERE id=?");
$result->execute(array($amount,$level,$etnl,$user));
} else {
$result = DB::getInstance()->prepare("UPDATE exp SET exp=? WHERE id=?");
$result->execute(array($amount,$user));
}
}`
`
but this system fails if the exp could level up a person 2 times any help or any new code? BTW etnl stands for exp till next level thank you
If you don't want to manually type out a level table like the other answer suggets you can also try doing your process with a recursive function:
$current_exp = 0;
$current_level = 1;
$to_next_level = 1000;
function did_level( $amount = 0 ) {
global $current_exp;
global $curent_level;
global $to_next_level;
$tmp_amount = $amount + $current_exp;
$tmp_amount_remainder = $tmp_amount - $to_next_level;
if ($tmp_amount >= $to_next_level) {
$current_level++;
$to_next_level *= 2;
$current_exp = $tmp_amount;
if ($tmp_amount_remainder > 0) {
// Level us up again.
did_level( $tmp_amount_remainder );
} else {
// Store the new level, to next level, and current exp
}
} else {
// Store the new exp amount
}
}
You have to get a table of levels which is basically a list of [exp, level] pairs. For example,
$level_list = [
['exp' => 0, 'level' => 1],
['exp' => 100, 'level' => 2],
['exp' => 1000, 'level' => 3],
// etc.
];
Then, you iterate the table starting from the end:
$i = count($level_list);
while($i > 0) {
$i--;
if ($user_exp >= $level_list[i]['exp']) {
// this is the level we need
break;
}
}
$target_level = $level_list[$i]['level'];
$target_exp = $level_list[$i]['exp'];

pChart a graph for each row

I'm new at using pChart. I take data from database to construct the graph.
I will have a random number of rows and I would like to do a graph for each row.
(one row -> one graph). Is it possible?
So far I can do the graph but all the rows are in the same graph.
Here is my code:
<?php
include("pChart/class/pData.class.php");
include("pChart/class/pDraw.class.php");
include("pChart/class/pImage.class.php");
include("pChart/class/pPie.class.php");
$myData = new pData();
$Requete = "SELECT * FROM `day`";
$Result = mysql_query($Requete, $db);
while($row = mysql_fetch_array($Result)){
$hour = explode(" ", $row["g1"]);
$nb = $row["numb"] * 2;
for($i = 0; $i < $nb; $i++){
if ($i%2 == 1){
$time[$i] = ($hour[$i])/ 60;
$myData->addPoints($time[$i],"year");
}else{
if ($hour[$i] == "00"){
$name[$i] = "On";
}elseif ($hour[$i] == "02"){
$name[$i] = "Off";
}
$myData->addPoints($name[$i],"name");
}
}
}
$myData->setAbscissa("name");
$myData->setSerieDescription("year","Application A");
$myPicture = new pImage(600,300,$myData);
$myPicture->setFontProperties(array("FontName"=>"pChart/fonts/tahoma.ttf","FontSize"=>16));
$PieChart = new pPie($myPicture,$myData);
$PieChart->draw3DPie(340,125,array("DrawLabels"=>TRUE,"Border"=>TRUE));
$myPicture->autoOutput("images/example.png");
?>
If I understand the question, you want a picture for every row? In that case I think that you will have to include the lower part of your code (starting from $myData to $myPicture) in the while loop.

Split total into 5 different numbers

Ok what i'm wanting to do is split a number ($row['count']) into 5, this is easy enough if you want equal numbers:
$sum = ($row['count'] / 5);
$fsum = floor($sum);
but I want each number to be different and still add up to total ie $row['count'] how can this be achieved?
Update:
If this helps its to be used to update 5 rows in a database:
$query = "SELECT * FROM foo";
$result = mysql_query($query);
while ($row = mysql_fetch_array($result)) {
$sum = ($row['count'] / 5);
$fsum = floor($sum);
$id = $row['id'];
$update = "UPDATE foo SET foo1='$fsum', foo2='$fsum', foo3='$fsum', foo4='$fsum', foo5='$fsum' WHERE id='$id'";
mysql_query($update);
}// while
so ideally the $update query would be something like:
$update = "UPDATE foo SET foo1='$fsum1', foo2='$fsum2', foo3='$fsum3', foo4='$fsum4', foo5='$fsum5' WHERE id='$id'";
This is my take:
function randomize($sum, $parts) {
$part_no = count($parts);
$continnue_counter = 0;
while (count(array_unique($parts)) != $part_no) {
$changing = array_rand($parts, 2);
if (($parts[$changing[0]] - 1) == 0 || ($parts[$changing[1]] - 1) == 0) { // don't let them go under 1
++$continnue_counter;
// sometime one element get everything and others even out on 1
// just throw away everything you got so far and start over
if ($continnue_counter > 10) {
$parts = setup($sum, $part_no);
$continnue_counter = 0;
}
continue;
}
$continnue_counter = 0;
$signum = mt_rand(0, 100) % 2 ? 1 : -1;
$delta = $signum * mt_rand(1, min($parts[$changing[0]] - 1, $parts[$changing[1]] - 1)); // -1 to make sure they don't go under 0
$parts[$changing[0]] += $delta;
$parts[$changing[1]] -= $delta;
}
return $parts;
}
function setup($sum, $part_no) {
$parts = array_fill(0, $part_no, (int)($sum / $part_no));
// acount for the reminder of (int) cast
$reminder = $sum - array_sum($parts);
while ($reminder) {
$parts[array_rand($parts)] += 1;
--$reminder;
}
return $parts;
}
$part_no = 5;
$sum = 42;
$parts = randomize($sum, setup($sum, $part_no));
var_export($parts);
print array_sum($parts)
Update:
I've added a version that introduces a little more entropy.
Update2:
The more random one had a tendency to decrement everything to 1 except one part, added an explicit detection to deal with this. Still the algorithm behind it has unknown termination time.

PHP MySQL read from a table to use in a graph

I have a graph that auto fills based on a few values. The values are the goal (total) the current (where it is at now) and in the total height of the graph. I am trying to pull the goal and current out of the database format it into money and it should fill the graph to the point it needs to be.
I had it working with a URL get which was ?current=584559096&goal=1000000000 and I just used $_GET. For easier maintenance for others around I want to pull it from a database which can be updated a post.
The code I have so far is:
<? php function formatMoney($number, $fractional=false) {
if ($fractional) {
$number = sprintf('%.0f', $number);
}
while (true) {
$replaced = preg_replace('/(-?\d+)(\d\d\d)/', '$1,$2', $number);
if ($replaced != $number) {
$number = $replaced;
} else {
break;
}
}
return $number;
}
$goal = $row['goal'];
$current = $row['current'];
$percent = round($current / $goal * 100);
$totalheight = 216;
$ourheight = $totalheight * $percent / 100;
$halfofarrowheight = 12;
$arrowheight = $totalheight-$ourheight-$halfofarrowheight;
if($arrowheight < 0)
$arrowheight = 0;
mysql_close($con);
?>
Here is my query
mysql_select_db("databasename", $con);
$result = mysql_query("select * from `dbname`.`tablename");
This is my error Warning: Division by zero in E:\inetpub\wwwroot\test.website.net\web\includes\globalfoot.php on line 36
Line 36 is the $percent = round($current / $goal * 100);
So, I been fooling with this thing for 4 days now trying to just get the numbers out of the goal column and current column format them to money and have the chart fill. For test sake lets say the goal is 1000000000000 and the current is 5000000000.
$row['goal'] = $goal;
$row['current'] = $current;
Please forgive me if I haven't understood your code, but shouldn't the above be:
$goal=$row['goal'];
$current=$row['current'];
Your code should look like this:
mysql_select_db("databasename", $con);
$result = mysql_query("select * from `dbname`.`tablename");
if (!$result || !($row = mysql_fetch_assoc($result))) {
echo "DB error: ".mysql_error();
exit;
}
$goal = $row['goal'];
$current = $row['current'];
// ...
Always, always double-check your variables when doing division.
$percent = ($goal > 0 || $goal < 0) ? round($current / $goal * 100) : 0;

Categories