Jump to content

How to sum, emit and store result from a calculation


u0867587
 Share

Recommended Posts

I have a calculation issue in my php. I want to add up all of the session marks ($row['Mark']} for each module and display the answer for each module at the end of each module name.  Below is my code:

 

   $output = "";
    $studentId  = false;
    $courseId  = false;
    $moduleId  = false;
    
        //BELOW IS THE CALCULATION IN PHP
        
        $moduletotal = 0;
        
        while ($row = mysql_fetch_array($result)){    
        	
            $moduletotal += $row['Mark'];
            
            $modulemark = (int)($moduletotal);
    
    //BELOW IS HOW PHP WILL DISPLAY THE RESULT
     ($modulemark is at the end of the 3rd (last) if statement)
              
    	if($studentId != $row['StudentUsername'])  {        
    			
    		$studentId = $row['StudentUsername'];        
    		$output .= "<p><strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']})";   
    			
    	   }    
    	   
    	   	if($courseId != $row['CourseId']) {    
    		
    		$courseId = $row['CourseId'];        		
    		$output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <br><strong>Year:</strong> {$row['Year']}</p>";    
    		
    		}    
    			 
    	if($moduleId != $row['ModuleId'])  {        
    				 
    	   $moduleId = $row['ModuleId'];        
    	   $output .= "<p><br><strong>Module:</strong> {$row['ModuleId']} - {$row['ModuleName']} $modulemark</p>";   
    				 
    	  }  
    	    
    	   $output .= "<p><strong>Session:</strong> {$row['SessionId']} {$row['Mark']}</p>";
    	
    
        			   
          }				 
      
    	echo $output;    }

 

 

BELOW IS THE RESULT IT SHOWS ON THE BROWSER:

 

    Student: Mayur Patel (u0867587)

    Course: INFO101 - Bsc Information Communication Technology 

    Year: 3

   

   

    Module: CHI2550 - Modern Database Applications 72 (72 is the answer to the calculation for the first module but this is incorrect at it should also add the 67 and thus become 139)

   

    Session: AAB 72

   

    Session: AAE 67

   

    Module: CHI2513 - Systems Strategy 200 (200 is the answer to the calculation for this module but this is incorrect it should be only 61. But what it has done is that it has added the 72 and 67 from the first module and added it with the 61 in this module)

   

    Session: AAD 61

 

 

It is obvious that I am not resetting $moduletotal to 0 when the module changes . I need to detect when to stop summing, emit and store the result, and then reset the counter. But I do not know to do this using php, can somebody please help me and provide a smaple code for this? Thank You

 

 

 

 

 

Link to comment
Share on other sites

Hmm, so you want to show the sum for the sessions in a module - but you want to display the module before the sessions? You'll need to take a different approach. I typically do this by creating a function for displaying a complete group and then use the trigger in the while() loop to call that function.

 

Not tested:

    function outputModule($moduleID, $moduleName, $sessionData)
    {
        if(!count($sessionData)) { return false; }

        $markTotal = 0;
        $sessionsHTML = '';
        foreach($sessionData as $session)
        {
            $sessionsHTML .= "<p><strong>Session:</strong> {$session['SessionId']} {$session['Mark']}</p>";
            $markTotal += $session['Mark'];
        }

        $moduleHTML = "<p><br><strong>Module:</strong> {$moduleID} - {$moduleName} {$markTotal}</p>";
        return $moduleHTML . $sessionsHTML;
    }

    $output = "";
    $studentId = false;
    $courseId  = false;
    $moduleId  = false;

    while ($row = mysql_fetch_array($result))
    {
        $moduletotal += $row['Mark'];
        $modulemark = (int)($moduletotal);

    	if($studentId != $row['StudentUsername'])
        {
            //Student has changed
    	    $studentId = $row['StudentUsername'];        
    	    $output .= "<p><strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']})";   
        }    
    	if($courseId != $row['CourseId'])
        {
            //Course has changed
            $courseId = $row['CourseId'];        		
            $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <br><strong>Year:</strong> {$row['Year']}</p>";    
        }    
    	if($moduleId != $row['ModuleId'])
        {
            //Module has changed
            if(isset($sessionsAry)) //Don't run function for first record
            {
                //Get output for last module and sessions
                $output .= outputModule($moduleId, $moduleName, $sessionsAry);
            }
            //Reset sessions data array and Set values for new module
            $sessionsAry = array();
            $moduleId    = $row['ModuleId'];
            $moduleName  = $row['ModuleName']
        }
        //Add session data to array for current module
        $sessionsAry[] .= array('SessionId'=>$row['SessionId'],'Mark'=>$row['Mark']);
    }

    //Get output for last module
    $output .= outputModule($moduleId, $moduleName, $sessionsAry);

    //Display the output
    echo $output;
}

Link to comment
Share on other sites

Hi, thanks for your answer but it has not quite worked,, it adds up the sessions very well for each module but it shows each session and module seperatly rather than together as I wanted it. e.g. If a module in a course has 2 sessions, it will show both sessions under that module but instead the code you have given me splits up the session and module so it will show the name of the module and one session and then it will show the module name again and then show the other session beneath that but I don't want that. Thanks for your attempt though much apprciated, if you have another idea then can you please share it with me or be able to edit the code you have game me?

Link to comment
Share on other sites

The code I provided should do exactly as you say you want. There must be a bug, I can't debug the code since I don't have your database.

 

The function outputModule() should only be called when there is a change in the module and that function should output the module (1 time) as well as all of the sessions associated with that module.

Link to comment
Share on other sites

When I use the code you have given me this is what it is outputting:

 

Student: Mayur Patel (u0867587)

Course: INFO101 - Bsc Information Communication Technology

Year: 3

 

 

Module: CHI2550 - Modern Database Applications 72

 

Session: AAB 72

 

Student: Mayur Patel (u0867587)

Course: INFO101 - Bsc Information Communication Technology

Year: 3

 

 

Module: CHI2550 - Modern Database Applications 72

 

Session: AAB 72

 

 

Module: CHI2550 - Modern Database Applications 72

 

Session: AAB 72

 

Student: Mayur Patel (u0867587)

Course: INFO101 - Bsc Information Communication Technology

Year: 3

 

 

Module: CHI2550 - Modern Database Applications 72

 

Session: AAB 72

 

 

Module: CHI2550 - Modern Database Applications 72

 

Session: AAB 72

 

 

Module: CHI2550 - Modern Database Applications 72

 

Session: AAB 72

 

 

Module: CHI2513 - Systems Strategy 61

 

Session: AAD 61

 

I can't understand what it is doing. Do you have any idea?

Link to comment
Share on other sites

The problem was with this line:

$sessionsAry[] .= array('SessionId'=>$row['SessionId'],'Mark'=>$row['Mark']);

 

Should have used "=" instead of ".=" which means to concatenate strings. I made some other changes during the debugging process, so I'm not sure that was the only problem. Here is the updated code which I have tested with some mock data

    function outputModule($moduleID, $moduleName, $sessionData)
    {
        if(!count($sessionData)) { return false; }

        $markTotal = 0;
        $sessionsHTML = '';
        foreach($sessionData as $session)
        {
            $sessionsHTML .= "<p><strong>Session:</strong> {$session['SessionId']} {$session['Mark']}</p>\n";
            $markTotal += $session['Mark'];
        }

        $moduleHTML = "<p><br><strong>Module:</strong> {$moduleID} - {$moduleName} {$markTotal}</p>\n";
        return $moduleHTML . $sessionsHTML;
    }

    $output = "";
    $studentId = false;
    $courseId  = false;
    $moduleId  = false;

    while ($row = mysql_fetch_array($result))
    {
        $moduletotal += $row['Mark'];
        $modulemark = (int)($moduletotal);
        if($studentId != $row['StudentUsername'])
        {
            //Student has changed
            $studentId = $row['StudentUsername'];        
            $output .= "<p><strong>Student:</strong> {$row['StudentForename']} {$row['StudentSurname']} ({$row['StudentUsername']})\n";   
        }

        if($courseId != $row['CourseId'])
        {
            //Course has changed
            $courseId = $row['CourseId'];        
            $output .= "<br><strong>Course:</strong> {$row['CourseId']} - {$row['CourseName']} <br><strong>Year:</strong> {$row['Year']}</p>\n";    
        }

        if($moduleId != $row['ModuleId'])
        {
            //Module has changed
            if(isset($sessionsAry)) //Don't run function for first record
            {
                //Get output for last module and sessions
                $output .= outputModule($moduleId, $moduleName, $sessionsAry);
            }
            //Reset sessions data array and Set values for new module
            $sessionsAry = array();
            $moduleId    = $row['ModuleId'];
            $moduleName  = $row['ModuleName'];
        }
        //Add session data to array for current module
        $sessionsAry[] = array('SessionId'=>$row['SessionId'], 'Mark'=>$row['Mark']);
    }

    //Get output for last module
    $output .= outputModule($moduleId, $moduleName, $sessionsAry);

    //Display the output
    echo $output;

Link to comment
Share on other sites

That has worked perfectly cheers. I did spot the .= problem before because it cam up with an error message on unexpected T_VARIABLE for that line but it must of been sometihng else you have changed to get it working.  Thank you very much, how you know a lot about php is beyond me, I am more of a database specialist than a programming specialist but you are the genius. You have helped me twice now and I really do appreciate it. Thank you again  :):D

Link to comment
Share on other sites

This thread is more than a year old.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

 Share

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.