as_reportool - File/program description
      

Login  
Password  
 
Registration





 
  Back to the list

as_reportool: Report building PHP class

This is another PHP class for building HTML report pages from SQL data. You just set the main SQL query, list of fields to be printed, and list of grouping fields, if You need sub-totals. All these data can be added by calling respective class methods or loaded from XML file (if your PHP is 5.x and simpleXML support is on).
This program is free and distributed under GNU GPL license.

Installation is standard - just copy as_reportool.php and as_dbutils.php class files to your site's folder, and add "include(), or require_once() for them to your php script file.

Using as_reportool library

require_once('as_reportool.php');
//...
$rep = new CReporTool();
First: You set an SQL query that returns all the data for report. Method SetQuery() is called to do this.
Next, You'll add all "fields" names that should be printed, in desired order, by AddField() method. Remember, these names must correspond with some field or expression's name in datarow.
For example, if your query contains something like "SELECT ... (field1+field2) `field1_field2`", to print this computed value in report, use "field1_field2" name:
$rep->AddField('field1_field2','F1 and F2 sum');

If You need some sub-totals (your query should return right ordered records in that case !), use a method AddGroupingField() to set "grouping" fields. Subtotals can be nested with no limit - the first field passed with AddGroupingField will be the "upper level", the next one will be the lower.
During getting data rows (and printing report) loop, when some "grouping" field value changes, all subtotals will be printed, beginning from the "lowest" level and up to this field's level in totals hierarchy.

Generated report is HTML code that looks adequate not only in the browser, but in the hard-printed page too. CSS styles used for this formatting are built-in into the class, but You can override them by calling SuppressCss() method. In this case "CSS style" block is not printed, so it's your responsibility to include all necessary styles somewhere in Your "style area". They are: td.rep_ltrb, td.rep_lrb, td.rep_rb, td.num, td.cnt, td.newgroup.

CReporTool class methods list

  • CReporTool([$filename [, $outcharset]]) - constructor can be used to load report definition from prepared XML file. Pass xml file name as a first parameter in new CReporTool() calling. If parameter missed, an empty CReporTool object will be created. The second parameter is used when Your output HTML page should be in non UTF-8 charset. Then you just pass your output charset name, and all string values (headers for fealds, grouping, total strings) loaded from XML file, will be converted to desired character set. (I noticed, that simpleXML function simplexml_load_file doesn't support parsing of non- UTF-8 files, it seams to ignore charset value in the header, so they must be written and saved in UTF-8 (alhough i may be wrong).
  • LoadFromXml($filename [,$outcharset='']) loads report definition from prepared XML file. When You create new object with calling new CReporTool($filename), constructor calls LoadFromXml(). The first parameter is a file name, the second one - output charset (see explanation above). The structure for XML file is shown here and is self-explanatory (that's why everybody's mad about XML :)
    If You plan using XML files, make sure Your hosting provider enables PHP5 with simpleXML support, because as_reportool uses simpleXML for XML files parsing !

    Here is XML file example
    
    <?xml version="1.0" encoding="UTF-8"?>
    <report_def version="1.00">
      <query>SELECT c.categoryid, b.animalid, a.nickname,a.gender,a.birth, a.weight
       FROM big_zoo a, animals b, animal_categories c
       WHERE a.animalid=b.animalid AND b.category=c.categoryid ORDER BY c.categoryid, b.animalid
      </query>
      <headings><![CDATA[
    <tr><td colspan="8" class="rep_ltrb">This is additional headings to print before default columns headings</td></tr>
    ]]></headings>
      <nodefaultheadings value="1" />
      <summary title="Summary totals (%rowcount%)" />
      <delimiters decimal="," thousand=" " />
      <grpfield name="categoryid" fconv="GetAnymalCategoryName" title="Animal category " totaltitle="Totals for category" />
      <grpfield name="animalid" fconv="GetAnymalClassName" title="Animal class" totaltitle="Totals for class" />
    
      <field name="nickname" title="Nick" fconv="" format="" />
      <field name="gender" title="Gender" fconv="DecodeGender" />
      <field name="weight" title="Weight, kg" summable="1" format="i" />
    
    </report_def>
    
    

  • query tag sets SQL query exactly as SetQuery() method does it.
    headings tag sets additional headings, like the method SetHeadings() does;
    nodefaultheadings with value="1" hides generated column headings, like SetHeadings($new_headings,1);
    grpfield tags is equal to calling AddGroupingField(),
    field tag used for AddField();
    summary tag used for SetSummary();
    delimiters tag is uqual to calling SetNumberDelimiters($decimal,$thousand).

  • AddGroupingField($fldid,$fconv='',$title='',$totaltitle='') adds a field that makes a group, so when changed, subtotals should be printed, followed by a header for the next grouping value.
    • $fldid is a field name (or pseudo-name for the data column as it given in sql query),
    • $fconv is a user (or php built-in) function name that will be called to convert data value before printing. For example, if the value is a numeric ID of department, this function is called to return department's name.
    • $title is a title that will be printed as a beginning of a new group, for example "department " for the new dept
    • $totaltitle is used as a header in the "subtotals" row. "%name%" macros will be replaced with current grouping field value, so if You pass "Totals for %name%", resulting subtotals line will begin with "Totals for Whales" or alike
    More than one grouping field can be added, to make multi-level sub-totals.


  • AddField($fldid,$fldtitle='',$summable=0,$fconv='', $format='') adds a printable field that makes a column in your report. Parameters:
    • $fldid is a field name (or pseudo-name for the data column as it given in sql query)
    • $fldtitle is a field's title used in the column's headings
    • $summable : if true (or any non-empty value), sub-totals for the field will be calculated/printed
    • $fconv is a function name that will be called to convert column's value before printing.
    • $format is optional formatting string identifier. Supported values for format listed below:
      formatmeaning (what it does)
      c"Centered" - value is centered horizontally
      r"Right" - value is right aligned
      moneyValue is number_format-ted as money (NNN NNN.00) and right aligned
      i"Integer" - is number_format-ted as integer (with thousands delimiter) and right aligned


  • SetHeadings($par, $no_defaultheader=0) : usually as_reportool generates simple headings for the report, using fields titles, that were passed by AddField() method.
    If You want sofisticated headings in your report, call method CReporTool::SetHeadings(). First parameter must be an HTML code that contains some table rows, starting with <tr> and with ending </tr>. This code will be echoed right after beginning TABLE tag, and before "default" heading row generated by class. If You have a FULL HTML code for the headings and don't want generated titles row, pass a second non-empty parameter $no_defaultheader, so it turns off default headings generation.


  • SetSummary($title) : if You want a "summary" row at the end of report, call this function. Use optional string parameter $title to pass the title string for that row, and if You want to see all printed rows count (not including subtotals!), include macro %rowcount% in this string - it will be replaced with the count.


  • SetNumberDelimiters($dec, $tho) sets delimiter chars for decimal part and thousands in number representations. These delimiters will be passed to number_format() for each field having 'i' or 'money' format. By default these delimiters are "," for thousands and "." for decimal part.


  • SetFontStyles($par) can be used to set css styles for the font used in report. For example, to draw all report with "verdana" font and size 3mm, pass a string :
    $rep->SetFontStyles("font-family: Verdana; font-size:3mm;");


  • DrawReport($title='') is a final method that executes passed SQL query, builds and echoes report body. Optional string parameter is a title that will be printed on top, before the report's headings.
  • Making report example.

    OK. Now let's describe some example data tables that we'll use to show reporting functionality. This is a "big zoo" database (our zoo is really big - it has a small "ocean" with oceanic animals like shark and even whale!). This DB has one table for animal categories, another one - for describing animals, and last one is a list of all animals living in the zoo. You can create these tables by running sql file included in distributive (sampledata.sql)

    fieldtypedescription
    table animal_categories
    categoryidINTunique category's ID
    categorynameVARCHARcategory name
    table animals
    animalidINTunique animal type's ID
    categoryINTcategory of the animal
    animalnameVARCHARanimal's name
    table big_zoo - all animals living in the zoo
    itemidINTliving creature's ID
    animalidINTwhat kind of animal is it (ID)
    nicknameVARCHARnick name given to this creature
    birthDATEbirth date
    genderCHAR(1)gender(m for male, f for female)
    weightINTcreature's weight


    We want to print report for all creatures in our zoo, with subtotals for every animal class and category.
    $rep = new CReporTool();
    
    $rep->SetQuery("SELECT c.categoryid, b.animalid, a.nickname,a.gender,a.birth,a.weight
       FROM big_zoo a, animals b, animal_categories c
       WHERE a.animalid=b.animalid AND b.category=c.categoryid ORDER BY c.categoryid, b.animalid");
    
    $rep->AddGroupingField('categoryid','GetAnymalCategoryName','Animal category ','Totals for category');
    
    $rep->AddGroupingField('animalid','GetAnymalClassName','Animal class ','Totals for class');
    
    $rep->AddField('nickname','Nick');
    
    $rep->AddField('gender','Gender',0,'DecodeGender'); // DecodeGender() will show 'male' for 'm' and female for 'f' value.
    $rep->AddField('birth','Birth date',0,'DateToChar'); // your function DateToChar converts DATE value to be more readable
    $rep->AddField('weight','Weight, kg',1,'','i'); // this field is summable and will be printed right-aligned and number_format()ted
    $rep->DrawReport('Report: All animals in zoo');
    
  • As You can see, our SQL query orders returned records by category and animal class, according to grouping fields passed to our CReporTool object.
    You may be want SQL server to build subtotals rows (using GROUP BY WITH ROLLUP option in MySQL, for example) - please don't do it, because CReporTool calculates totals by itself and cannot detect "totals" rows in returned SQL data.
  • As a result You should see report page like this one:

    Report: All animals in zoo

    NickGenderBirth dateWeight, kg
    Animal category Sea animals
      class : whales
     Whale-Boy male 06/22/1997 7,000
     Whale-Girl female 08/01/2000 6,500
    Totals for whales13,500
      class : sharks
     BloodyJaws male 09/15/2001 1,500
     HungryMary female 11/10/2002 1,200
    Totals for sharks2,700
      class : dolphins
     BigMartha female 05/20/1998 3,000
     BigBob male 01/12/1996 3,500
    Totals for dolphins6,500
    Totals for category Sea animals22,700
    Animal category Jungle animals
      class : elephants
     LazyTom male 10/23/2004 5,000
     MightyJack male 06/16/2003 5,300
     Samantha-Shy female 04/24/2004 4,200
    Totals for elephants14,500
      class : gorillas
     Gorilla-Mom female 08/23/2001 150
     Gorilla-Son male 04/15/2008 40
     Gorilla-Dad male 02/05/2000 180
    Totals for gorillas370
    Totals for category Jungle animals14,870
    Summary all animals (12) 37,570


    You can investigate included report_sample.php file as a starting point for your reports.

    Change log (Version history)

    1.00.002 (11/26/2008)
    First release
      Back to the list  
       votes :2
     
    Copyright © 2008-2010 selifan.ru