Using an Object to fill in a template

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • Claus Mygind
    Contributor
    • Mar 2008
    • 571

    Using an Object to fill in a template

    I am making a cross-tab report where essentially the data has to be turned sideways (rows to columns). My approach was to create a blank template object, cycle through the data and fill in the cells of the printed report. Making page breaks when the returned query data exceeded the size of the page template.

    For the fixed header information I have no trouble but when I try to create an array in the object to hold the variable number of column data, I cannot figure out how to reference / fill in the template.

    How do I reference the array I created in the pObj object? see code below.

    The following code illustrates my feeble attempt to do this. Ok this example is actually trying to use an array to store all the stuff. But I did try to use an object also.

    Code:
    function makePageObject($result, $row){
    
    	global $cPageCnt, $cRecCnt,$cBoring;
    	$pObj = array();
    
    	$pObj = array(
    		/*
    		------------------------------------------
    		page header info for specific boring
    		found in each row but only used on header
    		------------------------------------------
    		*/
    		$jobId    = $row["jobid"],
    		$boring   = $row["boring"],
    
    		/*
    		------------------------------------------
    		data section of page is a 11 X 22 table.
    		data can be more, less or equal to size of table
    
    		so I create an array with blanks
    		initialize array with blanks
    		------------------------------------------
    		*/
    		$colArray = array_fill(0, 22, array_fill(0, 10, " "))
    	);
    		//detail sample info for boring
    		while ($row = $result->fetch_array() and $cBoring == $row["boring"] and $cRecCnt < 11 ) 
    		{
    			/*
    			--------------------------------
    			build one column of sample data 
    			for each boring up to 10 samples 
    			per page
    
    			[B]How do I reference the array I
    			created in the pObj object?[/B]
    			--------------------------------
    			*/
    			[B]$colArray[/B][0][$cRecCnt]  = $row["boring"];
    			$colArray[1][$cRecCnt]  = $row["sample"];
    			$colArray[2][$cRecCnt]  = $row["depth"]; 
    			$colArray[3][$cRecCnt]  = $row["blows"];
    			$colArray[4][$cRecCnt]  = $row["sampleType"];
    			$colArray[5][$cRecCnt]  = $row["contNumb"];
    			$colArray[6][$cRecCnt]  = $row['WWofSC'];
    			$colArray[7][$cRecCnt]  = $row['DWofSC'];
    			$colArray[8][$cRecCnt]  = $row['contWeight'];
    			$colArray[9][$cRecCnt]  = $row['moisture'];
    			$colArray[10][$cRecCnt] = $row['sampleInAir'];
    			$colArray[11][$cRecCnt] = $row['sampleInWater'];
    			$colArray[12][$cRecCnt] = $row['water'];
    			$colArray[13][$cRecCnt] = $row['dryUnit'];
    			$colArray[14][$cRecCnt] = $row['dimDryUnit'];
    			$colArray[15][$cRecCnt] = $row['dimWeight'];
    			$colArray[16][$cRecCnt] = $row["dimDiameter"];
    			$colArray[17][$cRecCnt] = $row["qu"];
    			$colArray[18][$cRecCnt] = $row["percentFail"];
    			$colArray[19][$cRecCnt] = $row["qp"];
    			$colArray[20][$cRecCnt] = $row["tv"];
    			$colArray[21][$cRecCnt] = $row["soilDesc"];
    			//advance
    			$cRecCnt ++;
    		}
    
    	return $pObj;
    }
  • Dormilich
    Recognized Expert Expert
    • Aug 2008
    • 8694

    #2
    line #25 looks suspicious for an array definition ... usually there are no assignments in there. (though that is different for an object)

    hm, for the template, can’t you just reverse the nesting for the output?

    meaning:
    Code:
    // if you have
    for ($i = 0; $ < $length_lvl1; $i++) // row level
    {
      for ($j = 0; $ < $length_lvl2; $j++) // cell level
      {
        // do something with $array[$i][$j]
      }
    }
    
    // change it to
    for ($j = 0; $ < $length_lvl2; $j++) // row level
    {
      for ($i = 0; $ < $length_lvl1; $i++) // cell level
      {
        // do something with $array[$i][$j]
      }
    }

    Comment

    • Claus Mygind
      Contributor
      • Mar 2008
      • 571

      #3
      Thanks for the response.

      With regards to line 25, that one is actually right from the manual http://us.php.net/manual/en/function.array-fill.php

      I see what you are doing with the code by reversing the calls, I will study that in more details. My problem is they have cut my work back to just one day a week so I am getting a little rusty.

      I know what I want to do in concept, I just need to figure out how to write the code.

      1) create an object that represents the page content. That is create a class

      2) give the class some properties for the header information that does not change from page to page

      3) add a table array (an array of an array) that will take the variable data or insert a blank html tag

      4) add 4 methods that will process the data two for going in and two for taking it out. One of the two for the header and the other for the variable data (this is where I will use your coding example for handling the data)

      5) define a pObj (page object) from the class

      6) figure out how to call the methods to load and retrieve the data.

      That is a lot to ask here so I had better get some books and start studying.

      Comment

      • Claus Mygind
        Contributor
        • Mar 2008
        • 571

        #4
        Quick question do I still use the "include" statement if I define a class in the same code where I will call it.

        This link is a pretty good example of what I want to do.


        But I would like to just define the class and then write the access code just below it. I will not be needing this class in any other app. It just seems a sensible way to organize the data.

        Comment

        • Dormilich
          Recognized Expert Expert
          • Aug 2008
          • 8694

          #5
          With regards to line 25, that one is actually right from the manual
          I didn’t mean the array_fill() function, I meant the assignment.

          Quick question do I still use the "include" statement if I define a class in the same code where I will call it.
          no. if the code is already there, it doesn’t need to be included (otherwise you get an already defined error). nevertheless, I would always use autoloading and never define a class in the executing script.

          This link is a pretty good example of what I want to do.
          be aware that the var keyword is from PHP4. cf. http://php.net/oop


          I’ll get back later when I have more time to think about it.

          Comment

          • Claus Mygind
            Contributor
            • Mar 2008
            • 571

            #6
            Your help has been fantastic as usual. Also I have had a chance to read up on classes, so now I have a better overview of the process.

            Just a few notes on why I am doing it the way I am doing it.
            1) Time is only permitting me to do a straight conversion from my old dBase code to php (no time for improving it, so I am sticking as closely to the old procedural coding as possible)

            2) The returned result set from the query can create page breaks for 3 reasons. The data set is made up of:
            A) a job
            B) one or more borings
            C) a set of samples (variable number from 1 to infinity)

            To format the report with proper page breaks I use two loops that step through the $result set.

            An external loop, which simply continues until the end of the returned query.

            And a 2nd internal (within the class) loop that continues until a page break is needed.

            Page breaks should occur when
            1) the boring # changes
            2) for each 11 samples of a boring
            3) when the $result is at an end.

            Here is what I have developed for the internal loop. The actual streaming out of the data will occur in the external loop after I return a pObj (page object)

            Code:
            <?php
            function makePageObject($result, $row, $cPageCnt,$cBoring){
             
            	class pageObject
            	{
            		//properties
            		public jobId;
            		public boring;
            		public date;
            		public page;
            		public project;
            		public client;
            		public engineer;
            		public webUser;
            
            		//detail sample infor for boring
            		public colArray;
            
            		//methods
            		public __contruct( $result, $row, $cPageCnt,$cBoring ) {
            
            			//page header info for specific boring
            			$this->jobId	= $row["jobid"];
            			$this->boring	= $row["boring"];
            			$this->date		= $row["sampleDate"];
            			$this->page		= $cPageCnt;
            			$this->project	= $row['prjctname'].'<br/>'.
            							  $row['prjctaddr1'].' '.$row['prjctaddr2'].'<br/>'.
            							  trim($row['prjctcity'].', '.
            							  $row['prjctst'];
            			$this->client	= $row['name'].'<br/>'.
            							  trim($row['addr1'].' '.
            							  $row['addr2'].'<br/>'.
            							  trim($row['city']).' '.
            							  $row['st'].' '.
            							  zipConvert(trim($row['zip']));
            			$this->engineer	= $row['engineer'];
            			$this->webUser	= trim($row['webuser']);
            
            			//detail sample infor for boring
            			$this->colArray = array_fill(0, 22, array_fill(0, 11, "&nbsp;"));
            
            			$cRecCnt = 0;
            
            			//detail sample info for boring
            			while ($row = $result->fetch_array() and $cBoring == $row["boring"] and $cRecCnt < 11 ) 
            			{
            			    /*
            			    --------------------------------
            			    fill in columns with sample data
            			    --------------------------------
            			    */
            			    $this->colArray[0][$cRecCnt]  = $row["boring"];
            			    $this->colArray[1][$cRecCnt]  = $row["sample"];
            			    $this->colArray[2][$cRecCnt]  = $row["depth"]; 
            			    $this->colArray[3][$cRecCnt]  = $row["blows"];
            			    $this->colArray[4][$cRecCnt]  = $row["sampleType"];
            			    $this->colArray[5][$cRecCnt]  = $row["contNumb"];
            			    $this->colArray[6][$cRecCnt]  = $row['WWofSC'];
            			    $this->colArray[7][$cRecCnt]  = $row['DWofSC'];
            			    $this->colArray[8][$cRecCnt]  = $row['contWeight'];
            			    $this->colArray[9][$cRecCnt]  = $row['moisture'];
            			    $this->colArray[10][$cRecCnt] = $row['sampleInAir'];
            			    $this->colArray[11][$cRecCnt] = $row['sampleInWater'];
            			    $this->colArray[12][$cRecCnt] = $row['water'];
            			    $this->colArray[13][$cRecCnt] = $row['dryUnit'];
            			    $this->colArray[14][$cRecCnt] = $row['dimDryUnit'];
            			    $this->colArray[15][$cRecCnt] = $row['dimWeight'];
            			    $this->colArray[16][$cRecCnt] = $row["dimDiameter"];
            			    $this->colArray[17][$cRecCnt] = $row["qu"];
            			    $this->colArray[18][$cRecCnt] = $row["percentFail"];
            			    $this->colArray[19][$cRecCnt] = $row["qp"];
            			    $this->colArray[20][$cRecCnt] = $row["tv"];
            			    $this->colArray[21][$cRecCnt] = $row["soilDesc"];
            			    //advance
            			    $cRecCnt ++;
            			}
            		} 
            		$pObj = new pageObject( $result, $row, $cPageCnt,$cBoring );
            		return $pObj;
            	}
            ?>

            Comment

            • Claus Mygind
              Contributor
              • Mar 2008
              • 571

              #7
              with regards to my array_fill() function and assignment, I see the following in the php manual

              $a = array_fill(5, 6, 'banana');

              that appears to use the same assignment method which I use to create my array

              $this->colArray = array_fill(0, 22, array_fill(0, 11, "&nbsp;"));

              The only difference I am crating a 2 dimensional array, or as properly stated in php an array of arrays.

              Comment

              • Dormilich
                Recognized Expert Expert
                • Aug 2008
                • 8694

                #8
                that appears to use the same assignment method which I use to create my array

                $this->colArray = array_fill(0, 22, array_fill(0, 11, "&nbsp;"));
                that makes sense now. previously you had
                Code:
                $pObj = array(
                $jobId    = $row["jobid"],
                $boring   = $row["boring"],
                $colArray = array_fill(0, 22, array_fill(0, 10, "&nbsp;"))
                );
                which is somewhat strange for an array.

                PS. I never meant the use of array_fill() to be strange.

                Comment

                • Claus Mygind
                  Contributor
                  • Mar 2008
                  • 571

                  #9
                  yep! I agree, my original post was goofy. Still one error in my last post where I declare the properties of the class, I forgot to use the $ as in "public $jobid;"

                  Comment

                  • Claus Mygind
                    Contributor
                    • Mar 2008
                    • 571

                    #10
                    The correct response in this case was to learn how to create an object from a class

                    By defining a class with properties and methods, I was able to create a page object to fill in data.

                    The object contained several properties one of which was an array of arrays.

                    I initialized the array with a nested array_fill( array_fill()), that gave me a two dimensional array to transpose my data from query rows to table columns.

                    Then I created 3 methods (functions) to build and print may page object.

                    The first method was a constructor which I used to store my header information as well as create the table array.

                    The second method was to load data into the array until I needed a page break or I reached the end of the data

                    The last method I used to stream out each page as it was complete.

                    Here is a sample cross-tab report that can easily be modified for any type of two dimensional data.

                    Code:
                    <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
                    <?php
                    /* soilsLabPrintable.php - 
                        Author:	Claus Mygind
                    
                        Date:	6/25/2012 - php
                    
                    	Purpose: The purpose of this program is to create a multi-page cross tab report
                    
                    	It uses one embeded class to create page objects, which can be completed
                    	and then printed.
                    
                    */
                    try 
                    {
                    
                    	/*open connection to database*/
                    	include(my includes);
                    
                    	.... my query section .....
                    
                    	if ( $result = $db->query($sql) )
                    	{
                    		if ( $result->num_rows > 0)
                    		{
                    ?>
                    			<html>
                    				<head>
                    					<title>Printable cross tab report</title>
                    				</head>
                    
                    				<body>
                    					<form>
                    
                    <?php
                    					$cPageCnt = 1;
                    					$cRecCnt = 0;
                    					$cBoring = '';
                    
                    					/*
                    					here I loop through the query result,
                    					a page object is create if none exists
                    					a page is streamed out when the data
                    					calls for a page break or the end of the data
                    					*/
                    
                    					while ($row = $result->fetch_array()) 
                    					{
                    
                    						$cRecCnt ++;
                    
                    						if (!isset($pObj)){
                    							//set boring flag - used to flag a page break
                    							$cBoring = $row["boring"];
                    
                    							//create page object if not exists
                    							$pObj = new pageObject($row, $cPageCnt);
                    							$pObj->loadRow($row, $cRecCnt);
                    
                    
                    						}else if($cBoring != $row["boring"] or $cRecCnt > 10){
                    
                    							//page breaks are created when there are more than
                    							//10 samples or the next boring number is encountered.
                    
                    							//print page object if new boring or record count has exceeded page
                    							$pObj->printPage();
                    
                    							//insert page break
                    							echo '<span class="newPage"></span>';
                    
                    							//re-initilize control variables
                    							
                    							//reset record counter
                    							$cRecCnt = 1;
                    
                    							//reset boring flag
                    							$cBoring = $row["boring"];
                    
                    							//destroy page object
                    							unset($pObj);
                    
                    							//advace page count
                    							$cPageCnt ++;
                    
                    							//create new page object
                    							$pObj = new pageObject($row, $cPageCnt);
                    							$pObj->loadRow($row, $cRecCnt);
                    
                    						}else{
                    							//add row data to page object
                    							$pObj->loadRow($row, $cRecCnt);
                    						}
                    					}
                    
                    					if (isset($pObj)){
                    						//some data is left to print
                    						$pObj->printPage();
                    						
                    						//destroy page object
                    						unset($pObj);
                    					}
                    
                    ?>
                    					</form>
                    				</body>
                    			</html>
                    <?php
                    		}else{
                    			throw new Exception("No records found!");
                    		}
                    
                    	}else{
                    		throw new Exception("Query failed.");
                    	}
                    }
                    
                    catch (exception $e) 
                    {
                    	echo 'An error occured : ' .$e->getMessage();
                    }
                    
                    class pageObject
                    {
                    	//properties
                    	public $jobId;
                    	public $boring;
                    	public $date;
                    	public $page;
                    	public $project;
                    	public $client;
                    	public $engineer;
                    	public $webUser;
                    
                    	//detail sample infor for boring
                    	public $colArray;
                    
                    	//methods
                    	public function __construct( $row, $cPageCnt ) {
                    		/*
                    		this method is called when a new page object is created
                    		*/
                    
                    		//page header info for specific boring
                    		$this->jobId	= $row["jobid"];
                    		$this->boring	= $row["boring"];
                    		$this->date		= $row["sampleDate"];
                    		$this->page		= $cPageCnt;
                    		$this->project	= $row['prjctname'];
                    
                    		/*
                    		detail information is stored in a cross-tab table 
                    		where the query rowset is transposed into columns
                    
                    		the table is inintialized with the required number
                    		of cells. each cell is seeded with blank html tag
                    		*/
                    		$this->colArray = array_fill(0, 22, array_fill(0, 11, "&nbsp;"));
                    		/*
                    		-------------------
                    		fill in row headers 
                    		-------------------
                    		*/
                    		$this->colArray[0][0]  = "Boring";                                            
                    		$this->colArray[1][0]  = "Sample #";                                          
                    		$this->colArray[2][0]  = "Depth in Feet";                                     
                    		$this->colArray[3][0]  = "No. of Blows";                                      
                    		$this->colArray[4][0]  = "Type";                                              
                    		$this->colArray[5][0]  = "Container Number";                                  
                    		$this->colArray[6][0]  = "Wet weight of<br/>Sample + Container";              
                    		$this->colArray[7][0]  = "Dry weight of<br/>Sample + Container";              
                    		$this->colArray[8][0]  = "Weight of container";"Percent moisture";            
                    		$this->colArray[9][0]  = "Percent moisture"; 		              
                    		$this->colArray[10][0] = "Weight of sample in air";                           
                    		$this->colArray[11][0] = "Weight of sample in water";                         
                    		$this->colArray[12][0] = "Weight of water";                                   
                    		$this->colArray[13][0] = "Disp. Dry unit weight in<br/>pounds per cubic foot";
                    		$this->colArray[14][0] = "Dim. Dry unit weight in<br/>pounds per cubic foot"; 
                    		$this->colArray[15][0] = "Dry unit scale weight";                             
                    		$this->colArray[16][0] = "Dimension<br/>(Diameter * Length)";                  
                    		$this->colArray[17][0] = "Qu (TSF)";                                          
                    		$this->colArray[18][0] = "Qu % failure";                                      
                    		$this->colArray[19][0] = "Qp (TSF)";                                          
                    		$this->colArray[20][0] = "Tv";                                                
                    		$this->colArray[21][0] = "Soil description"; 
                    
                    	}                                
                    
                    	public function loadRow($row, $cRecCnt){
                    		/*
                    		--------------------------------
                    		fill in columns with sample data
                    		--------------------------------
                    		*/
                    
                    		$this->colArray[0][$cRecCnt]  = ( empty($row["boring"] ))		?"&nbsp;" :$row["boring"];
                    		$this->colArray[1][$cRecCnt]  = ( empty($row["sample"] ))		?"&nbsp;" :$row["sample"];
                    		$this->colArray[2][$cRecCnt]  = ( empty($row["depth"] ))		?"&nbsp;" :$row["depth"]; 
                    		$this->colArray[3][$cRecCnt]  = ( empty($row["blows"] ))		?"&nbsp;" :$row["blows"];
                    		$this->colArray[4][$cRecCnt]  = ( empty($row["sampleType"] ))	?"&nbsp;" :$row["sampleType"];
                    		$this->colArray[5][$cRecCnt]  = ( empty($row["contNumb"] ))		?"&nbsp;" :$row["contNumb"];
                    		$this->colArray[6][$cRecCnt]  = ( $row['WWofSC'] == 0)			?"&nbsp;" :$row['WWofSC'];
                    		$this->colArray[7][$cRecCnt]  = ( $row['DWofSC'] == 0)			?"&nbsp;" :$row['DWofSC'];
                    		$this->colArray[8][$cRecCnt]  = ( $row['contWeight'] == 0)		?"&nbsp;" :$row['contWeight'];
                    		$this->colArray[9][$cRecCnt]  = ( $row['moisture'] == 0)		?"&nbsp;" :$row['moisture'];
                    		$this->colArray[10][$cRecCnt] = ( $row['sampleInAir'] == 0)		?"&nbsp;" :$row['sampleInAir'];
                    		$this->colArray[11][$cRecCnt] = ( $row['sampleInWater'] == 0)	?"&nbsp;" :$row['sampleInWater'];
                    		$this->colArray[12][$cRecCnt] = ( $row['water'] == 0)			?"&nbsp;" :$row['water'];
                    		$this->colArray[13][$cRecCnt] = ( $row['dryUnit'] == 0)			?"&nbsp;" :$row['dryUnit'];
                    		$this->colArray[14][$cRecCnt] = ( $row['dimDryUnit'] == 0)		?"&nbsp;" :number_format($row['dimDryUnit'], 1, '.', '');
                    		$this->colArray[15][$cRecCnt] = ( $row['dimWeight'] == 0)		?"&nbsp;" :number_format($row['dimWeight'], 1, '.', '');
                    		$this->colArray[16][$cRecCnt] = ( $row["dimDiameter"] == 0)		?"&nbsp;" :$row["dimDiameter"];
                    		$this->colArray[17][$cRecCnt] = ( empty($row["qu"] ))			?"&nbsp;" :$row["qu"];
                    		$this->colArray[18][$cRecCnt] = ( empty($row["percentFail"] ))	?"&nbsp;" :$row["percentFail"];
                    		$this->colArray[19][$cRecCnt] = ( empty($row["qp"] ))			?"&nbsp;" :$row["qp"];
                    		$this->colArray[20][$cRecCnt] = ( empty($row["tv"] ))			?"&nbsp;" :$row["tv"];
                    		$this->colArray[21][$cRecCnt] = ( empty($row["soilDesc"] ))		?"&nbsp;" :$row["soilDesc"];
                    
                    	}									                                              
                    
                    	public function printPage(){
                    ?>
                    		<table 
                    			bgcolor="#FFFFFF"
                    			width="100%"
                    		>
                    		  <tr>
                    			<td colspan="2">Job #: <span class="subHeading3"><?php echo $this->jobId ?></span>
                    			&nbsp;Boring #: <span class="subHeading3"><?php echo $this->boring ?></span> Date: <span class="subHeading3"><?php echo $this->date ?></span></td>
                    			<td align="right">Page: <span class="subHeading3"><?php echo $this->page ?></span></td>
                    		  </tr>
                    		  <tr>
                    			<td><span class="subHeading3">Project: </span><?php echo $this->project ?></td>
                    		  </tr>
                    		</table> 
                    		<table 
                    			bgcolor="#FFFFFF"
                    			border="1"
                    		>
                    
                    <?php
                    
                    		for ($i=0; $i <= 21; $i++) {
                    			echo '<tr>';
                    			//set row back ground color
                    			if ($i == 9 or $i == 13 or $i == 14 or $i == 17 or $i == 19){
                    				$cCol="#E0E0E0";
                    			}else{
                    				$cCol="#FFFFFF";
                    			}
                    
                    			echo '<td width="15%">'.$this->colArray[$i][0].'</td>';
                    			echo '<td width="8.5%" style="text-align:center;background-color:'.$cCol.';">'.$this->colArray[$i][1].'</td>';
                    			echo '<td width="8.5%" style="text-align:center;background-color:'.$cCol.';">'.$this->colArray[$i][2].'</td>';
                    			echo '<td width="8.5%" style="text-align:center;background-color:'.$cCol.';">'.$this->colArray[$i][3].'</td>';
                    			echo '<td width="8.5%" style="text-align:center;background-color:'.$cCol.';">'.$this->colArray[$i][4].'</td>';
                    			echo '<td width="8.5%" style="text-align:center;background-color:'.$cCol.';">'.$this->colArray[$i][5].'</td>';
                    			echo '<td width="8.5%" style="text-align:center;background-color:'.$cCol.';">'.$this->colArray[$i][6].'</td>';
                    			echo '<td width="8.5%" style="text-align:center;background-color:'.$cCol.';">'.$this->colArray[$i][7].'</td>';
                    			echo '<td width="8.5%" style="text-align:center;background-color:'.$cCol.';">'.$this->colArray[$i][8].'</td>';
                    			echo '<td width="8.5%" style="text-align:center;background-color:'.$cCol.';">'.$this->colArray[$i][9].'</td>';
                    			echo '<td width="8.5%" style="text-align:center;background-color:'.$cCol.';">'.$this->colArray[$i][10].'</td>';
                    			echo '</tr>';
                    		}
                    
                    		echo '</table>';
                    	}
                    }
                    ?>

                    Comment

                    Working...