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;
Related
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.
I am working on a bit of PHP and I've come upon a bit of issues.
I am using PHP to randomly choose a number from 1-360. I am trying to compare the answer to a list of value determined by range.
$NumberA = rand(0,180);
$NumberB = rand(0,180);
$NumberC = $NumberA + $NumberB;
if ($NumberC = range(0,21) {
$result = "Orange";
}
elseif ($NumberC = range(22,42) {
$result = "Red";
}
elseif ($NumberC = range(43,63) {
$result = "Blue";
}
//This goes on for a while ...
else {
$result = "Green";
}
echo = $result;
Anytime i do this, the result always assigns the value of "Orange" to $result .
Im sure im doing something wrong here, please help!
First of all, you used just one '=' to compare while it should have been '=='. Second range() generates an array and you cannot compare an integer to an array. Third why generating the range every single time when you can check that $NumberC lies between the minimum and the maximum numbers of the range?
Change your code to:
$NumberA = rand(0,180);
$NumberB = rand(0,180);
$NumberC = $NumberA + $NumberB;
if ($NumberC >= 0 && $NumberC <= 21) {
$result = "Orange";
} elseif ($NumberC >= 22 && $NumberC <= 42) {
$result = "Red";
} elseif ($NumberC >= 43 && $NumberC <= 63) {
$result = "Blue";
} else {
$result = "Green";
}
echo $result;
Shall work. Hope this helps.
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.
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.
I Keep getting the following error and I was wondering on how to fix it.
Fatal error: Unsupported operand types on line 97
Its around this area of code listed below. I can list the full code if needed.
PHP code
$total_rating_points = mysqli_fetch_array($result);
if (!empty($total_rating_points) && !empty($total_ratings)){
$avg = (round($total_rating_points / $total_ratings,1));
$votes = $total_ratings;
echo $avg . "/10 (" . $votes . " votes cast)";
} else {
echo '(no votes cast)';
}
Here is Line 97
$avg = (round($total_rating_points / $total_ratings,1));
Here is the full code.
function getRatingText(){
$dbc = mysqli_connect ("localhost", "root", "", "sitename");
$page = '3';
$sql1 = "SELECT COUNT(*)
FROM articles_grades
WHERE users_articles_id = '$page'";
$result = mysqli_query($dbc,$sql1);
if (!mysqli_query($dbc, $sql1)) {
print mysqli_error($dbc);
return;
}
$total_ratings = mysqli_fetch_array($result);
$sql2 = "SELECT COUNT(*)
FROM grades
JOIN articles_grades ON grades.id = articles_grades.grade_id
WHERE articles_grades.users_articles_id = '$page'";
$result = mysqli_query($dbc,$sql2);
if (!mysqli_query($dbc, $sql2)) {
print mysqli_error($dbc);
return;
}
$total_rating_points = mysqli_fetch_array($result);
if (!empty($total_rating_points) && !empty($total_ratings)){
$avg = (round($total_rating_points / $total_ratings,1));
$votes = $total_ratings;
echo $avg . "/10 (" . $votes . " votes cast)";
} else {
echo '(no votes cast)';
}
}
$total_rating_points is an array. you cannot divide it by a number.
(edited since the MySQL query was added to the question)
You've used mysql_fetch_array to get your result from MySQL, as the name suggests this returns an array. You can't do math like that on arrays.
You want to change your MySQL query to this:
$sql1 = "SELECT COUNT(*) as count
FROM articles_grades
WHERE users_articles_id = '$page'";
Change your mysql_fetch_array code to this:
$total_rating_points = mysql_result($result, 0, "count");
That will return the actual number, which you can then use for math. Change both of your queries to this format and you should be good to go.
That's usually caused when the type of one of your variables is something you're not expecting it to be.
$x = "8";
$y = 4;
$x / $y; // this is OK, PHP converts "8" to 8
$x = new FooObject();
$y = 4;
$x / $y; // PHP says "wtfmate??"
Dump out the variables $total_rating_points and $total_ratings:
var_dump($total_rating_points);
var_dump($total_ratings);
.. then work backwards through your code (checking debug_backtrace() if required) to find where it went awry.
Edit: duhhh.. I just looked at your code again and saw the issue. The $total_rating_points is an array, and this is the cause of the problem. How do you divide an array by a number? Answer: you can't.
Do you want to divide each of the members of the array by $total_ratings? eg:
// input: [2, 4, 6, 16] / 2
// output: [1, 2, 3, 8]
function divideArrayMembers($arr, $denominator) {
$ret = array();
foreach ($arr as $key => $val) {
$ret[$key] = $val / $denominator;
}
return $ret;
}
...or do you want to divide the total?
input: [2, 4, 6, 16] / 2
output: 14 // (2 + 4 + 6 + 16) / 2
function divideTotal($arr, $denominator) {
return array_sum($arr) / $denominator.
}
Use array_sum() on $total_rating_points and $total_ratings.
if($_REQUEST['cityCode'] != ''){
$_SESSION['Cri_locations'] = $_REQUEST["s"];
$_SESSION['Cri_DateFrom'] = $_REQUEST["startDate"];
$_SESSION['Cri_DateTo'] = $_REQUEST["endDate"];
$what_to_search_id =str_replace("AREA-","",$_REQUEST["cityCode"]);
$total_adults =0;
$total_childs =0;
$child_ages =0;
$no_of_room =0;
for($i=1;$i<=$_REQUEST["Cri_noofRooms"];$i++){
$check_adults =$_REQUEST['adults-r'.$i.''];
if($check_adults>0){
$adults =$_REQUEST['adults-r'.$i.''];
$childs =$_REQUEST['childs-r'.$i.''];
$childAge =$_REQUEST['childAge-r'.$i.''];
$packs_arr[] =array('adults'=>$adults,'childs'=>$childs,'childAge'=>$childAge);
$total_adults =$total_adults+$adults;
$total_childs =$total_childs+$childs;
$child_ages =$child_ages+$childAge;//error accours here pls help
$no_of_room =$no_of_room+1;
}
}