Improve company productivity with a Business Account.Sign Up

x
  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 308
  • Last Modified:

counting total

I have the code below working. I need the total for $finalcharge as in total charges. How do I display the total amount charged with $finalcharge? I am just displaying all the result in one page where adding a total amount charged would be ideal.

if ($calltype!='4'){

              $finalcharge = $actualcharge*$price;

                  <tr><td>xxx</td><td>".$finalcharge."</td></tr>\n");

  }
0
rolandmy
Asked:
rolandmy
  • 8
  • 6
  • 2
  • +2
2 Solutions
 
webhansonCommented:
Hi rolandmy,

The code presented does not appear to be complete. Could you send a full example of the code you are using and more clearly state what you require?

Thanks
0
 
Chris StanyonCommented:
Can you clarify what you need. Can't see what you want from the code you've posted, as the code you've posted doesn't seem valid (you seem to be missing the 'echo' part).

If you want a running total, you can do something like:

$total = 0;

//start of a loop
    $finalcharge = $actualcharge*$price;
    echo $finalcharge;
    $total += $finalcharge;
//finish loop

echo $total;

Open in new window

0
 
rolandmyAuthor Commented:
I need to display the total amount for $finalcharge. It is at the moment displaying line by line with individual charges.

Code as below:

while($row = mysqli_fetch_array($result))
  {
  $calledpartynumber=$row['CalledPartyNumber'];
  $durationtime=$row['DurationTime'];
 
  $answer = substr($calledpartynumber, 0, 5);
 
  $answer2 = substr($answer, 0, 1);
 
  $billing = substr($answer, 0, 2);
 
  if ($billing=='01') {
      $price='0.82';
        } elseif ($billing=='02') {
        $price='0.09';
      } elseif ($billing=='00') {
            if ($answer=='00818') {
                  $price='0.99';
            } elseif ($answer=='00852') {
                  $price='0.88';
            }
  }
 
  $charge = $durationtime/30;
 
  if ( preg_match("/\./", $charge) ) {
        $actualcharge = intval($charge) + 1;
        }else{
              $actualcharge = intval($charge) + 0;
              }
 
  if ($calltype!='4' && $durationtime!='00' && $answer2!='1'){
        if ($callingpartynumber=='2233'){
              $finalcharge = $actualcharge*$price;
  print("<tr><td>$durationtime</td><td>".$finalcharge."</td></tr>\n");
        }
  }
  }
mysqli_close($con);
0
Free Tool: IP Lookup

Get more info about an IP address or domain name, such as organization, abuse contacts and geolocation.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

 
Julian HansenCommented:
I don't really know for sure what you are asking but I suspect this might be along the lines of what you are looking for
while($row = mysqli_fetch_array($result))
  {
  $calledpartynumber=$row['CalledPartyNumber'];
  $durationtime=$row['DurationTime'];
 
  $answer = substr($calledpartynumber, 0, 5);
 
  $answer2 = substr($answer, 0, 1);
 
  $billing = substr($answer, 0, 2);
 
  if ($billing=='01') {
      $price='0.82';
        } elseif ($billing=='02') {
        $price='0.09';
      } elseif ($billing=='00') {
            if ($answer=='00818') {
                  $price='0.99';
            } elseif ($answer=='00852') {
                  $price='0.88';
            }
  }
 
  $charge = $durationtime/30;
 
// You are dealing with this in another question so won't fix here.
  if ( preg_match("/\./", $charge) ) {
        $actualcharge = intval($charge) + 1;
        }
/* THIS IS SUPERFLUOUS - YOU CAN REMOVE IT
else{
              $actualcharge = intval($charge) + 0;
              }
*/
 
  if ($calltype!='4' && $durationtime!='00' && $answer2!='1'){
        if ($callingpartynumber=='2233'){
              $finalcharge += $actualcharge*$price;
        }
  }
  }
  print("<tr><td>$durationtime</td><td>".$finalcharge."</td></tr>\n");
mysqli_close($con); 

Open in new window

0
 
Chris StanyonCommented:
Have a look at this. Declare a variable to hold the total before the loop starts, add the relevant values within the loop, and then echo out the total after the loop:

<?php 

$totalCharge = 0;

while($row = mysqli_fetch_array($result)) {
	
$calledpartynumber=$row['CalledPartyNumber'];
$durationtime=$row['DurationTime'];
 
$answer = substr($calledpartynumber, 0, 5);
$answer2 = substr($answer, 0, 1);
$billing = substr($answer, 0, 2);
$finalcharge = 0;

if ($billing=='01') {
	$price='0.82';
} elseif ($billing=='02') {
	$price='0.09';
} elseif ($billing=='00') {
	if ($answer=='00818') {
		$price='0.99';
	} elseif ($answer=='00852') {
		$price='0.88';
	}
}
 
$actualcharge = ceil($durationtime/30);
 
if ($calltype!='4' && $durationtime!='00' && $answer2!='1'){
	if ($callingpartynumber=='2233'){
		$finalcharge = $actualcharge*$price;
	}
}

$totalCharge += $finalcharge;

}

printf("<p>%s</p>", $totalCharge);

mysqli_close($con); 
?>

Open in new window

0
 
rolandmyAuthor Commented:
Currently the display are like below:

| Duration | Charges |
|     37       |     0.18   |
|     20       |     0.09   |
|    etc...

How can I get the total amount for Charges which value is derived from $finalcharge
0
 
Chris StanyonCommented:
Already given you the answer - read through my previous post.
0
 
Chris StanyonCommented:
You might want to change line 39 of my previous comment to the following:

printf("<tr><td>Total</td><td>%s</td></tr>", $totalCharge);

Open in new window

0
 
rolandmyAuthor Commented:
0
 
Julian HansenCommented:
@Chris - nice cleanup on the code there but is there not a potential logic bomb here?
if ($calltype!='4' && $durationtime!='00' && $answer2!='1'){
	if ($callingpartynumber=='2233'){
		$finalcharge = $actualcharge*$price;
	}
}

$totalCharge += $finalcharge;

Open in new window

The original post seems to indicate that $finalcharge is only calculated when callingpartynumber is 2233. In your solution though it is increasing totalcharge each time it loops irrespective.
0
 
Chris StanyonCommented:
@julian - earlier in my code (inside the loop) the $finalcharge value is reset to 0, so although it does add it each time, unless the logic matches, it simply adds 0 - that was to address the logic problems that currently exist throughout the code - i.e. finalcharge not existing at all unless the if statement fired)
0
 
Chris StanyonCommented:
@rolandmy - check your code again - case matters, so make sure it matches:

$totalCharge is not the same as $totalcharge
0
 
rolandmyAuthor Commented:
Updated the case.

The $totalCharge result shows 2293.83 whereas the actual total doesn't even reach 200.

I have re-attached the full code.
sample.php
0
 
Chris StanyonCommented:
Add the following to the very top of your code, and re-run it - it will show you any errors you have (I'm guessing there will be some).

<?php 
error_reporting(E_ALL);
ini_set('display_errors', 1)
?>

Open in new window

You do have a strange approach to some of your logic that may or may not fail depending on the data coming out of your database.
0
 
rolandmyAuthor Commented:
Initially have a undefined variable $finalcharge at the bottom. I moved it up and there's no error anymore.

The $totalCharge result is now 762.93 where it should be less than 200.

I have also attached a sample file.

Please help. Going to sleep at this time. Will check again in 6 hours.
sample.php
0
 
Ray PaseurCommented:
I think you could make this a lot easier on yourself if you adopted a coding standard.  Such things call for the use of reasonable variable names, explicit error checking, consistent indentation, etc.  Basically a coding standard will make your code easier to read and less at risk for bugs, especially run-time failures.  You might also want to switch over to the object-oriented notation for MySQLi since it will require much less punctuation (and hence less opportunity for parse errors).  Some good learning resources for PHP are available in this article.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_11769-And-by-the-way-I-am-new-to-PHP.html

I also think you might want to simplify the logic here.  The number of if() statements could probably be reduced a lot if you refactor the code.  For example, it appears that you have a dependency between Bill_Import.CalledPartyNumber and PHP variable $price.  This dependency could be removed from the code and implemented in a lookup table.  That way if new values are needed in the computations, or prices change, etc., you would not have to change your programming.

As written, if Bill_Import.CalledPartyNumber starts with '02' $price will be undefined or will be left equal to the value that was last set.  You might want to look into that.  Anyway, good luck with it, ~Ray
0
 
Chris StanyonCommented:
Have a look at this. Haven't tested it, but it's a more logical approach to your problem. Read through the code and take on board what Ray's said and you should be heading in the right direction:

<?php 
//make sure you see all the errors
error_reporting(E_ALL);
ini_set('display_errors', 1);

//connect to your database
$con=mysqli_connect("localhost","xxx","xxx","xxx");
if (mysqli_connect_errno()) { die("Failed to connect to MySQL: " . mysqli_connect_error()); }

//select only the rows we need
$result = mysqli_query($con,"SELECT * FROM Bill_Import WHERE (CallType != '4' AND DurationTime != '00' AND SUBSTRING(CalledPartyNumber, 1, 1) != '1')");

//create a variable to hold the overall total 
$totalCharge = 0;

//loop through the records
while($row = mysqli_fetch_array($result)) {
	
	//we only need to output a row if the CallingPartyNumber matches certain values
	switch ($row['CallingPartyNumber']) {
		case '0005':
		case '0006':
		case '0007':
		case '0008':
			//set some default values
			$price = 0;
		
			$areaCode = substr($row['CalledPartyNumber'], 0, 5);
			$billingCode = substr($row['CalledPartyNumber'], 0, 2);
			$timeMultiplier = ceil($row['DurationTime'] / 30);

			//figure out what price to charge
			switch ($billingCode) {
				case '00':
					if ($areaCode == '00818') {
						$price = 0.5;
					} elseif ($areCode == '00852') {
						$price = 0.1;
					}
					break;
					
				case '01':
					$price = 0.12;
					break;
			
				case '03':
					$price = 0.09;
					break;
			};
	
			//now we can calculate the row charges
			$rowCharges = $timeMultiplier * $price;
			
			//output a table row
  			printf("<tr><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td><td>%s</td></tr>",
				$row['DialedNumber'],
				$row['CallType'],
				$row['CallingPartyNumber'],
				$row['CalledPartyNumber'],
				$areaCode,
				$row['DurationTime'],
				$rowCharges
			);
			
			//increment the total charge
			$totalCharge += $rowCharges;
	};

}

//now output the running total
printf("<tr><td colspan=6>Total</td><td>%s</td></tr>", $totalCharge);

?>

Open in new window

0
 
rolandmyAuthor Commented:
I followed the code exactly, it's much better. However, the $totalCharge remains wrong. It's only a slight difference though. Could be human error. I will recalculate with a calculator and update here again.

The $rowCharges are correct though.

Edit: It's human error. Thanks for the solution.

Will read up on Ray's comment.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Free Tool: Subnet Calculator

The subnet calculator helps you design networks by taking an IP address and network mask and returning information such as network, broadcast address, and host range.

One of a set of tools we're offering as a way of saying thank you for being a part of the community.

  • 8
  • 6
  • 2
  • +2
Tackle projects and never again get stuck behind a technical roadblock.
Join Now