Solved

counting total

Posted on 2013-07-01
18
297 Views
Last Modified: 2013-07-01
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
Comment
Question by:rolandmy
  • 8
  • 6
  • 2
  • +2
18 Comments
 
LVL 2

Expert Comment

by:webhanson
ID: 39290455
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
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39290466
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
 
LVL 2

Author Comment

by:rolandmy
ID: 39290512
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
 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39290528
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
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39290548
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
 
LVL 2

Author Comment

by:rolandmy
ID: 39290557
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
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39290561
Already given you the answer - read through my previous post.
0
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39290578
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
 
LVL 2

Author Comment

by:rolandmy
ID: 39290598
0
IT, Stop Being Called Into Every Meeting

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 
LVL 51

Expert Comment

by:Julian Hansen
ID: 39290600
@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
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39290612
@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
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39290623
@rolandmy - check your code again - case matters, so make sure it matches:

$totalCharge is not the same as $totalcharge
0
 
LVL 2

Author Comment

by:rolandmy
ID: 39290649
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
 
LVL 42

Expert Comment

by:Chris Stanyon
ID: 39290672
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
 
LVL 2

Author Comment

by:rolandmy
ID: 39290718
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
 
LVL 108

Assisted Solution

by:Ray Paseur
Ray Paseur earned 50 total points
ID: 39290820
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
 
LVL 42

Accepted Solution

by:
Chris Stanyon earned 300 total points
ID: 39290912
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
 
LVL 2

Author Comment

by:rolandmy
ID: 39292034
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

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Introduction Knockoutjs (Knockout) is a JavaScript framework (Model View ViewModel or MVVM framework).   The main ideology behind Knockout is to control from JavaScript how a page looks whilst creating an engaging user experience in the least …
Password hashing is better than message digests or encryption, and you should be using it instead of message digests or encryption.  Find out why and how in this article, which supplements the original article on PHP Client Registration, Login, Logo…
The viewer will learn how to create and use a small PHP class to apply a watermark to an image. This video shows the viewer the setup for the PHP watermark as well as important coding language. Continue to Part 2 to learn the core code used in creat…
This tutorial will teach you the core code needed to finalize the addition of a watermark to your image. The viewer will use a small PHP class to learn and create a watermark.

760 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now