Vol

OCTOBER 2004 VOLUME NO. 1 ISSUE NO. 3 DataObjx L.L.C. Website: www.dataobjx.net

DataObjx L.L.C. Meriden, CT USA

Office: 860/919-2536

Email: [email protected]

Website: www.dataobjx.net

DataObjx L.L.C.

Extra: Building A In This Issue Document Management Dynamic Sub Menus - In this article we examine a technique that will enable you to System - Part 1 for rapidly create and integrate a sub-menu system for the various sections of your website. This method allows for dynamic link generation and allows you to create as many separate PHP Included In sub menus as you want. This Issue. Building A Document Management System Part 1 – PHP - Included in this issue is the conversion of “Part 1” of the Document Management System. Translated By Sixto Santos. If you’re a PHP developer, download Issue #1 in conjunction with this article and code.

Dynamically Formatting Row Colors – PHP -In this article the technique used to dynamically alter the color of a row () is discussed. Read this article in conjunction with Issue #1.

Producing Excel Spreadsheet Using The PHP Common Interface -In this article Fernando Sibaja explains how you can produce excel spreadsheets for any table or query using the PHP Common Interface.

Need More Answers? Building A Document Management System – Part 3 -We wrap up our three (3) part Click here to access the Code series on building a document management system. Together we’ll integrate Check-In and Charge Studio Forums Check-Out capability plus the ability to un-do a check out. Core document management functionality is now at your disposal. Editors Comments Viewpoint...

In our third (3rd) issue we complete the core functionality for our Document Management System.

We also demonstrate a technique that will allow you to build menus dynamically for your ‘sub-pages’. A method that you will find useful in a number of situations.

Encapsulated within both of these articles are various methods and techniques that will make building your next application much easier.

We also have a number of PHP articles contributed by Fernando Sibaja and Sixto Santos. Both of these developers have years of experience and share some of their knowledge with you by providing you with real world examples.

Furthermore, Sixto Santos has translated Part 1 of the Document Management System – so PHP developers – take note.

In addition, we really need your help to keep this magazine relevant to the types of applications that you’re building today.

We cannot stress how important your feed-back is to us and we encourage you to write to [email protected] with your suggestions.

Once again, we’re asking for CodeCharge Studio developers within the community to contribute to this initiative by writing an article for CCS Developer Magazine. This is very important to us because and to you – our readers.

We hope you enjoy issue #3 of CCS Developer Magazine.

Best Regards,

Martin Hamilton www.dataobjx.net

CCS Developer Page 1

Language: .ASP Expanding The CodeCharge Studio Portal – Part 2 Database: N/A Building Navigational Menus With CCS.

Finding A Menu the project directory of your choice. important to understand that the menu does not offer many of the slick features When we build applications with If the project file is already open, you found in many of the more powerful CodeCharge Studio, we often find may need to perform a right click on the java script menus. ourselves presented with an ever-growing top node of CCS Page Tree and execute number of menu options. a refresh of the project files. However, in some instances where a ‘finite set of options’ are available for a Some developers choose to implement a New Cascading Style Sheet (CSS) ‘given’ page, this simple yet effective menu system immediately while others File tend to wait until they know what the method is often more than ample. Notice that the style sheet file is called menu options will be in the end. Since the application that you build may menu_1_styles.css (plural). This file have more than one page requiring a Regardless of whether you fall into the contains the CSS styles used by the sub-menu (each with their own relative first group, the second group or demonstration. Refer to Figure One (1). somewhere in between you still find that links), we’re going to encapsulate all of you need to integrate ‘sub-level’ Some web sites have slightly different the functionality that’s needed into an navigation into certain areas of your colors/branding depending on which include file. This makes it easy to application. area of the site a visitor is on. modify and maintain each menu and provides an easy mechanism by which The technique demonstrated in this It’s not always practicable to implement a menu’s are kept separated. high-end menu system in every minor article allows you to use a different style section either and often, these menus are sheet for each menu. Simply copy and Finally, notice how we maintained a java script driven and have hard coded save the menu_1_styles.css file with modular approach to the menu. The values – while you likely require another name and modify your menu’s entire logic and code necessary for the dynamically generated links. CSS file reference accordingly. menu to work is encapsulated in the menu file itself. For example, let’s say that you have a The menu_1_styles.css file contains a medium to large application. For our number of additional CSS definitions The remaining files simply have the example, let’s say that it’s an integrated that will make your menu more menu file inserted as an include file. attractive, but feel free to add additional package that contains within it – a mini This makes this code very transportable attributes such as background-images, email type package. and enables you to utilize this technique mouse_over code and so forth. The email package would have additional rapidly in any application that you build. You may be surprised at the number of links relating only to it, such as In Box, Once you’ve worked your way through attributes being set by the CSS Sent Items, etc. the article and code, you’ll begin to see definitions, but this is necessary if we spots where you can immediate apply You want to keep these links relative to want browsers other than IE to render the technique in your own applications. the page the user is on (the email page) the page properly. and therefore do not want to place such Creating The Menu Include links on the primary menu system. The CSS in this file has been tested under IE 6.0, FireFox 0.10.1 and We begin by creating a new page with You want them to be encapsulated and Netscape 7.1 and appears to render the includable property set to yes. available only when the user is within the similarly – at least for these versions. Since we may have more than one email package of your application. menu in our application, we should Generate and publish all of the files, adopt some naming convention that will We’re going to show you a technique you then open your browser to your project enable us to rapidly locate such menu can use that will enable you to produce a and open the menu_test.asp page. relatively dynamic menu system. files. We chose to use “menu_” as the Click on each of the menus. You should prefix for any such menu file. The menu will dynamically light up the see each menu options toggle/change When you create your own menu, you menu option relating to the page you’re color and linking dynamically as you might save this new page as on, and can be graphically enhanced by click on each page. adjusting the CSS styles. menu_YourWebSiteArea. Before We Get Under The Hood Putting Things Into Context In this example however, the menu Before we begin to look at the code, it’s page itself is called Open the zip file that accompanies this important to realize that this type of “menu_test_menu.ccp”. article and copy all of the menu_test… menu system is certainly not applicable Open this file files and the menu_1_styles.css file into to every situation. Furthermore, it’s CCS Developer Page 2

Expanding The CodeCharge Studio Portal – Part 2 Language: .ASP Database: N/A Building Navigational Menus With CCS, continued…

Since we need to add label controls to Figure 1 *{ the page, CCS tells us that we need to padding:0; create a record/form and prompts us border-style:0; margin:0; to generate the necessary code. We } .MenuSelected{ decided to call the record - ‘menu’. border-left-width : 1; border-bottom-width : 1; Click on the HTML tab and you’ll border-right-width : 1; border-top-width : 1; notice that we’ve modified the HTML border-left-style : solid; for the table slightly, because we are border-bottom-style : solid; border-right-style : solid; going to dynamically create the border-top-style : solid; border-left-color : #C0C0C0; “…” blocks of code in the border-bottom-color : #000000; before_show event for the record. border-right-color : #000000; border-top-color : #C0C0C0; padding-left : 2; The benefit of doing the padding-bottom : 2; “…” blocks this way is that padding-right : 1; padding-top : 1; we are able to programmatically margin-left : 1; margin-bottom : 1; control the number of columns with margin-right : 1; code rather than hard coding the margin-top : 1; color: white; columns into a HTML table simply by background-color: blue; font-size: 11px; adding another label and plugging in font-weight: bold; the necessary code. font-family : Verdana, Arial, Helvetica, sans-serif; } .MenuNormal{ While we’re on the HTML tab, also border-left-width : 1; notice that the menu_1_styles.css border-bottom-width : 1; border-right-width : 1; page has been included. This means border-top-width : 1; border-left-style : solid; that each menu_pagename can use border-bottom-style : solid; it’s own menu_websitearea_styles.css border-right-style : solid; border-top-style : solid; file. border-left-color : #C0C0C0; border-bottom-color : #000000; border-right-color : #000000; If we didn’t put the style sheet inside border-top-color : #C0C0C0; the menu itself, you’d be forced to padding-left : 2; padding-bottom : 2; add the CSS File link in every page padding-right : 1; using the menu. padding-top : 1; margin-left : 1; margin-bottom : 1; This is not a good idea, keep things margin-right : 1; margin-top : 1; modularized as much as you can. color: #000000; That way, you create more and more background-color: #C0C0C0; font-size: 11px; modular objx’s (sorry ‘objects’) that font-weight: bold; font-family : Verdana, Arial, Helvetica, sans-serif;} you can use over and over again in your projects and applications. .MenuSubCaptionTD{ border-left-width : 1; border-bottom-width : 1; How Does The Menu Work? border-right-width : 1; border-top-width : 1; Essentially, whenever we need font-weight: bold; font-family : Verdana, Arial, Helvetica, sans-serif;} CONTINUED IN CSS FILE……. another menu option to our menu, we’ll simply add another label control and set its content type to HTML.

Click on the first label {lnkHome} in there are two global variables The GetPageName() Function our example page. Select the Events dimensioned and there is a function called The purpose of the GetPageName tab and perform a right click – show ‘GetPageName()’. code on the before_show event for function is, as you may have guessed the label. This is the controlling function for the – to programmatically let you know dynamic menu, so we need to understand what page is being executed. Now scroll all of the way up to the top its function and purpose. Refer To Figure When the function executes, it of the _events.asp page. Notice that two (2). CCS Developer Page 3

Expanding The CodeCharge Studio Portal – Part 3 Language: .ASP Database: N/A Building Navigational Menus With CCS, continued…

populates the two (2) global variables Figure 2 - Function GetPageName() <% with the appropriate path and name Dim szPath information. Dim szPage

NOTE: This function may need further Public Function GetPageName(zPath, zPage) tweaking if you have a deeply nested 'On Error Resume Next directory structure. Dim strCurrentPageName Dim pos To see the function in action, remove strCurrentPageName = Request.ServerVariables("SCRIPT_NAME") the apostro phes from the two (2) pos = InStrRev(strCurrentPageName, "/") response.write statements in the zPath = UCase(Mid(strCurrentPageName, 1 ,pos)) zPage = UCase(Mid(strCurrentPageName, pos+1 ,Len(strCurrentPageName))) menu_test_menu_BeforeShow() event. zPage = Replace(zPage, "/", "") Doing so will cause the same End Function %> information that is being populated to the global variables to be displayed.

Now that we know how the menu the menu link as a label. When we need to display the menu option with derives the name of the page that the navigate off of the Home page, the a corresponding link. user has accessed, the rest is simply menu should display the link to the Generating Menu Links logic and CSS. home page as a link. Dynamically How Does The Menu Change Like The logic therefore is relatively Figure three (3) demonstrates the That? simple. If the name of the page code used to create the menu links returned by the GetPageName() The effect that we want to achieve here dynamically. function is the same as the page that is to cause the “Link” to be a href link if the user is currently on, then we need We’ve also included in the example the user is not on the page for that to display the menu option as a label. the way that you would use to include action. In other words, if they’re on the If the page names do not match we any querystring parameters that are home page, the menu should display

Figure 3 - labelname_BeforeShow() Dim sPageNameToMatch ‘The Name Of the Page To Match To The Global szPage variable Dim ID ‘Example querystring param being passed to this page Dim sHREF ‘holds the dynamic href string Dim sResult ‘the final result to be placed in label.value Dim sTitle ‘the title to be displayed for the menu option Dim startTD ‘the starting tag Dim EndTD ‘the ending tag Dim sCSSClass ‘the name of the class to be used – dynamic, based on page name Dim sCaption ‘a sub caption to display additional instructions for information

sPageNameToMatch = UCase("menu_test.asp") sTitle = "Home" ID = Request.Querystring("id") sCSSClass = "MenuNormal"

If szPage = sPageNameToMatch Then sCSSClass = "MenuSelected" sHREF = sTitle sCaption = "Select An Option..." menu_test_menu.menu.lblCaption.value = sCaption Else sHREF = "" & sTitle & "" End If

startTD = "" endTD = "" sResult = startTD & sHREF & endTD

menu_test_menu.menu.lnkHome.value = sResult CCS Developer Page 4

Expanding The CodeCharge Studio Portal – Part 2 Language: .ASP Database: N/A Building Navigational Menus With CCS, continued…

Screen Shot display to the user. And finally, the sCCSClass will dynamically cause the .menunormal or .menuselected style to be displayed.

Some of you may also have noticed that there is an additional definition at the top of the style sheet. Refer to

Figure five (5).

When you click on a link, the applicable page will be loaded. As the page loads, a check This is a CSS hack that causes is made to determi ne whether the name of the .asp page is matches the name of the virtually all browsers to properly align page required by the before_show event of the label. themselves. Using this in your CSS If they match, a title is displayed. If they don’t match, an appropriate link is displayed. files will assist you in achieving a consistent appearance regardless of being sent to the page. This example the browser your visitor is using. Figure 5 – A Special CSS Tag dimensions and uses the “ID” variable. Now that you know how to easily You would rename this according to the *{ implement a basic dynamic menu into variable being passed to your page and padding:0; your applications, you’ll find plenty of if more variabl es were required you border-style:0; use for this technique. would simple dimension them and add margin:0; them to the ‘sHREF’ string. } This method is useful for both production and is especially useful if The important variables are; This is an important CSS tag you need to have a simple form of that you should automatically navigation while you’re building your • sPageNameToMatch, include in all of you style application, even if you intend to • sTitle, sheets. swap it out later should you find you need something more. Quite often, • sCaption and • sCSSClass CCS Marketplace The sPageNameToMatch variable is Sell Your CodeCharge Studio Projects On Line! probably the most important. Since we’re looking at the before_show event What Is The CCS Marketplace? of {lnkHome}, you’ll notice that the The CCS Marketplace is an on-line store where you can buy and sell CCS Project files or variable sPageNameToMatch is the applications. name of the “Home Page” or menu_test.asp. What Type Of Applications Are Sold At The CCS Marketplace?

Quickly scan the before_show events for You can sell any type of application you like on the CCS Marketplace [ provided they’re the other labels and you’ll notice that in within the law of course ;) ]. You can also sell ‘snippets’ of code if you wish. each case, the name of the page that What About Copyright? the link would otherwise access is the

name of the page the label represents. As a developer you should be aware of copyright laws and how they protect your intellectual property. To learn more about copyright laws, search the intranet and read So, there’s no mystery here. If you’re the many articles on-line. on the page that the label represents, the function displays sTitle as well, a What About Licensing? You will need to create your own pricing structure and license information to go along Title - and if you’re on another page with each product you sell on-line. You may have one price for the run-time files and (and thus the page name you’re on another price that includes the CCS files. Furthermore, your license may be broken doesn’t match the sPageNameToMatch down to licensed seats or perhaps with no restrictions at all. variable for the label, you’ll get a href instead. How Do I Get My Product Onto The CCS Marketplace? Contact DataObjx advising us of your intent and we’ll get back to you with the The caption should reflect whatever information we need to place your product on-line.

additional information you want to

CCS Developer Page 5

Building A Document Management System – Part 1 / PHP Language: .PHP Database: MySQL Part 1 Of A Three Part Series …

Editors Comment the “Code Language” is set to .PHP. Access Database that accompanies this article or you may point it to your In our first issue, we began building If necessary, select .PHP as the “Code MySQL database. our Document Management System Language” for publication. using .ASP Note: This code is intended to be Also, ensure that the publication path to the executed with a DSN pointed at your CCS Magazine is pleased to announce DocumentManager directory on your web MySql database. server is correct. the conversion of that code from .ASP to .PHP. and we extend our thanks to Now You Can Generate The PHP Create The DSN! Mr. Sixto Sant os for the next two Code… conversions. Having implemented the data schema Now, generate the code, publishing it mentioned earlier in this article; and having If you haven’t downloaded issue 1 of CCS Developer to the DocumentManager directory on Magazine (FREE) yet, you may want to because the checked the project settings mentioned in your web server. article explains what the application is doing and why this article. it’s being done. Open your web browser and point it You now need to refer to the Document It is assumed that the reader has downloaded Issue to the appropriate location on your Management System Article in Issue #1 of #1 of CCS Developer Magazine and is familiar with web server. the logic and explanations provided in the relevant CCS Developer Magazine. article. Locate the section relating to “Creating The ODBC/DSN Connection” for and create the Document Manager Pro – DocManager DSN. PHP Edition Setting Up The Database Available Soon on the CCS You may choose to point this DSN at the MS Locate the “DocManager_MySQL.sql” Marketplace…. file or highlight and copy the SQL located in Figur e two (2). You can see the .PHP code in action at; Use this SQL to create the tables, etc. required by the application. http://docmanager.tecnoapoyo.com/documentmanager/Login.php

You will need to copy the Username is admin, password 1 or guest1, password 1 “dbUpload.php ” & “test_download.php” files from your development directory to the NOTE: DocumentManager directory on your Mr. Santos pointed out that… web server. One small detail that you should be aware of is that the maximum filesize for the PHP version is 1MB. This is so because the default installation of MySQL restricts input Ensure that you open both of these packages (hence queries) to that size. It is possible to have bigger packages, but that files and modify the database would require a redefinition of the max_allowed_package runtime parameter, something connection settings appropriately. that may be impossible to modify if using a shared hosting service.

Generating The Document About Manager Sixto Luis Santos

Create a directory on your web server Mr. Santos has been an IT Consultant and Professional for 15 years. and create a directory on your development machine. We will call He started developing applications in CodeCharge since the early days, and moved to that directory DocumentManager. CodeCharge Studio as soon as it was released.

Unzip the file: His expertise is in PHP and MySQL, but also develops traditional desktop applications in C/C++ and Visual Basic. DocumentManager_ASP+PHP.zip He is 34 years old, married, with two daughters Andrea and Ariana, and a still unborn son, to the DocumentManager directory on soon to be called Bryan. your development machine. Open the DocumentManager.ccs file (with CodeCharge Studio) and ensure that the project settings indicate that CCS Developer Page 6

Building A Document Management System – Part 1 / PHP Language: .PHP Database: MySQL Part 1 Of A Three Part Series …

Figure 2 - MySQL Data Schema For DocManager Application # Database : docmanager

CREATE TABLE `DocumentManagerDepartments` (

`id` int(11) NOT NULL auto_increment,

`file_area` varchar(50) NOT NULL default '',

PRIMARY KEY (`id`)

) TYPE=MyISAM;

INSERT INTO `DocumentManagerDepartments` (`id`, `file_area`) VALUES (1, 'Tools (Public)');

INSERT INTO `DocumentManagerDepartments` (`id`, `file_area`) VALUES (2, 'Source Code (Public)');

INSERT INTO `DocumentManagerDepartments` (`id`, `file_area`) VALUES (3, 'Components (Public)');

# ------

CREATE TABLE `DocumentManagerUpload` ( Incorporate A Jobs Board On Your `UploadID` int(11) NOT NULL auto_increment, Web Site! `user_id` int(11) NOT NULL default '0',

`UploadDT` datetime NOT NULL default '0000-00-00 00:00:00', If you’re trying to get a Jobs Board set up for `Title` varchar(50) NOT NULL default '', a client or for your web site there’s no better place to start than the DataObjx Jobs Board. `Description` text NOT NULL, st `Keywords` text NOT NULL, Available 1 Week Of November, 2004

`DataSize` int(11) NOT NULL default '0',

`Data` mediumblob, The commercial release of the Jobs Board will be available on the CCS Marketplace. `ContentType` varchar(64) NOT NULL default '',

`SourceFileName` varchar(128) NOT NULL default '', This is a far more advanced application than the Jobs Board currently in use on DataObjx. This `file_area` int(11) NOT NULL default '0', commercial version of the DataObjx Jobs Board now allows any type of occupation, job or project to `publish` smallint(6) NOT NULL default '0', be advertised. `times_downloaded` int(11) NOT NULL default '0', Packed with other features like PRIMARY KEY (`UploadID`),

KEY `IDX_KEYWORDS` (`Keywords`(128)) • Improved Service Buyer To Service Provider negotiation process, ) TYPE=MyISAM;

# ------• Better support for email communication,

CREATE TABLE `users` ( • No restrictions to occupations being advertised. `User_ID` int(11) NOT NULL auto_increment,

`user_login` varchar(20) NOT NULL default '', Why not have a look for yourself

`user_password` varchar(20) NOT NULL default '', There are 2 licenses available `first_name` varchar(50) NOT NULL default '', • Licensed To A Web Site - $119.99 • Developer License - $249.99 `last_name` varchar(50) NOT NULL default '', There is also a support and minor upgrades and `title` varchar(50) NOT NULL default '', patches option. `group_id` int(11) NOT NULL default '0', THIS SOFTWARE IS NOT OPEN-SOURCE OR PUBLIC PRIMARY KEY (`User_ID`) DOMAIN SOFTWARE. THIS SOFTWARE IS ) TYPE=MyISAM; PROTECTED BY INTERNATIONAL COPYRIGHT LAW.

INSERT INTO `users` (`User_ID`, `user_login`, `user_password`, `first_name`, `last_name`, `title`, `group_id`) VALUES (1, 'Admin', '1', 'The', 'Administrator', 'Site Administrator', 5);

INSERT INTO `users` (`User_ID`, `user_login`, `user_password`, `first_name`, `last_name`, `title`, `group_id`) VALUES (2, 'guest1', '1', 'guest', 'level 1', 'Level 1 Guest', 1);

CCS Developer Page 7

Formatting Row Colors / PHP Language: .PHP Database: MS Access Changing Row Color According To Database Values…

Editors Comment Alternatively, if you want to recreate the Generate and publish the default.ccs page again so that the In this second conversion, Mr. Santos Northwind ‘Products’ Table using translates the .ASP code from our first changed default_events.php file is issue to .PHP. MySQL, you can run the script – transferred to your web server.

“northwind_products_MySQL.sql” If you haven’t downloaded issue 1 of CCS Developer Open your web browser and point it Magazine (FREE) yet, you may want to because the to the appropriate location on your You now need to refer to the Formatting article explains what the application is doing and why web server. it’s being done. Row Colors Article in Issue #1 of CCS Developer Magazine. Refer to the article located in Issue It is assumed that the reader has downloaded Issue #1 for more information about #1 of CCS Developer Magazine and is familiar with Now You Can Generate The PHP dynamically formatting row colors. the logic and explanations provided in the relevant article. Code… As you’ll discover, all of the real Now, generate the code, publishing it to work occurs in the the DocumentManager directory on your Products_Hidden1_BeforeShow() web server. function. Create a directory on your web server and create a directory on your Replacing The default_events.php development machine. We will call that file Send Us Your Article directory RowColors. After you have generated and published Unzip the file: the code to the RowColors table, you What are you waiting for? will need to replace the default_events RowColors_PHP.zip file with the one found in the zip file that accompanies this article. Get your article published to the RowColors directory on your in the next issue of CCS development machine. This saves you the time of re-typing the code. Developer Magazine! Open the RowColors.ccs file (with CodeCharge Studio) and ensure that the project settings indicate that the “Code function Products_Hidden1_BeforeShow() Language” is set to .PHP. function Products_Hidden1_BeforeShow() { If necessary, select .PHP as the “Code $Products_Hidden1_BeforeShow = true; Language” for publication. //End Products_Hidden1_BeforeShow

Also, ensure that the publication path //Custom Code @10-B8559C5D // ------to the RowColors directory on your web global $Products; server is correct. $sStyle = "OliveDataTD"; //Default Style

Create The NorthWind Products $NumUnitsInStock = $Products->ds->f("UnitsInStock"); Table Using MySQL //handle any null values Warning! if(strlen($NumUnitsInStock)==0) $NumUnitsInStock=0; The SQL script referred to below will create a table called ‘Products’. if($NumUnitsInStock < 6) $sStyle = "OliveRedDataTD"; If your MySQL database already elseif($NumUnitsInStock > 6 && $NumUnitsInStock < 21) contains a table called ‘Products’, you $sStyle = "OliveOrangeDataTD"; may need to alter the name of the table elseif($NumUnitsInStock > 20 && $NumUnitsInStock < 51) in the SQL script before you run it - so $sStyle = "OliveYellowDataTD";

that you do not mistakenly modify your real ‘Products’ table. $Products->Hidden1->SetValue($sStyle); // ------//End Custom Code If you want to use the Northwind Database that comes with this article //Close Products_Hidden1_BeforeShow @8-4DE10D30 return $Products_Hidden1_BeforeShow; point the database connection to the } Northwind.mdb file. If you haven’t //End Close Products_Hidden1_BeforeShow copied this file into the RowColors directory you may want to do so now. ?> CCS Developer Page 8

The CodeCharge-PHP Common Database Interface. Using It Language: .PHP To Produce MS-EXCEL Reports Database: Oracle/Sybase Written By: Fernando Sibaja-Araya. Figure 1 – Connection Strings ([email protected]) $link_ID=OCIplogon ("user","password","database") or die("Connection failed"); $query_ID = OCIParse($link_ID, "SELECT * FROM TABLE"); PHP provides a wide variety of database OCIExecute($query_ID); support. Everybody knows that its set of database extensions is one of the PHP $link = sybase_connect('server', “user”, “password”) features that make it so popular and or die("Connection failed"); accepted. sybase_select_db(“db”,$link) $query_ID = sybase_query("SELECT * FROM TABLE", $link); Although PHP’s lack of database standardization is an obstacle to properties depending of the database you want to know if a specific query is building database-independent engine, we will show just the common empty then you’ll have to call this applications. stuff. method at least once.

Each database extension has its own set Since PHP4 isn’t a really object oriented f(String index), f(int index) of functions and these are defined to language and doesn’t have access Returns the value of the column fulfill the needs or conception of its modifiers we’ll just show the methods that indicated by index. engine. should be public, but the classes have

many more. You must call to next_record() before. As an example of this, we show two you can use the string identifier used code fragments that do the same thing Properties: in the query or the ordinal number of (just execute an SQL statement), but the field. for two different databases: ORACLE DBHost and SYBASE. The database server name or IP. close()

Releases the resources used by the Refer To Figure 1. Some databases like ORACLE don’t make connection.

use of this. The disadvantage of PHP developing Be sure to close the connections that without any framework (well, one of DBDatabase you use after every query. them), is that if the developer doesn’t The database name. use some kind of database class library, Believe it or not, these four methods then porting the application to another are all you need to know to perform database would be a complex and all the database tasks that you will buggy work. DBUser have to. The user name or schema.

In the last example we can notice how For example, refer to Figure 2. the inherent differences between the DBPassword

databases engines make the connection The password. As we all know (and if you don’t then process a whole different thing. you should), the key idea behind of Construction: CodeCharge Studio developing is to Fortunately we use a framework, we use avoid as much as possible - the CodeCharge Studio, and the people The constructor name depends of the custom code - and try to do all the from YesSoftware Inc. have done their name that you use for your database tasks through the IDE. homework very well - designing a connection, and has the form

common database library class. DatabaseName, where prefix is Although some kind of functionalities “clsDB”. like excel or pdf’s reporst have to be The advantages of the managed with a couple of tricks. CCPCDC(Codecharge-PHP common For example if you call your connection

database class) are the following. “myDatabase” then the class name will be Now that we have explained the clsDBmyDatabase. Common Database Interface we will • It uses the native extension use this knowledge to create a functions provided by PHP, so The assignation of the database properties reusable excel report library. there is no need of additional (DBHost, DBDatabase, DBUser,

software installation. DBPassword) is made by extending the The excel reports • You have access to its generic class, so you just have to take

implementation, so you can care of these values using the design Ok, let’s face it. truly understand how it works. view.

• You have a visual From the receptionist to the executive administration tool to manage Methods: manager everybody uses excel, it has your connections as objects become a very common information from the IDE, so change across query(String queryString) interchange media. databases wouldn’t be easier. Executes the query specified in

queryString. A that performs excel CodeCharge-PHP Common database reports would allow your customers to interface API. boolean next_record() have the information directly in a Fetches the next query’s row. Return true format that they can manipulate and Each implementation has different if a new row is retrieved, false if not. If CCS Developer Page 9

The CodeCharge-PHP Common Database Interface. Using It Language: .PHP Database: Any To Produce MS-EXCEL Reports

Figure 2 – Example Figure 3 – BiffWriter Class Methods /* If you already have used a grid or a recordSet with a datasource in the $Biff->xlsWriteText //writes text in a cell of the page, a connection instance will be already created in the page and can matrix by accessed using de global keyword , is better to use this instead of $Biff->xlsWriteNumber //writes a number in a cell creating a new one. If you do need to create a new connection then you of the matrix just have to do it this way: $Biff->xlsSetFont //sets a $dbmyDatabase = new clsDBmyDatabase(); $Biff->xlsAddFormat( */ $Biff->xlsSetPrintGridLines(); global $dbmyDatabase; $Biff->xlsSetPrintHeaders(); $Biff->xlsHeader $dbmyDatabase->query(“SELECT COL1, COL2 FROM MY_TABLE”); echo “Printing query results…\n”; while($dbmyDatabase->next_record()){ How To Obtain Biffwriter echo “col1: ”. $dbmyDatabase->f(“COL1”) . “col2: ” . $dbmyDatabase->f(1),”\n”; } The Biffwriter, developed by Chirstian Novak. $dbmyDatabase->close(); (www.cnovak.com)

manage, that would make them functions in it: happy (or at least they would smile - autoXlsReport_simple For example, if you use ORACLE and more often). - autoXlsReport_fliped you have a query like this;

In this article we will use one libraries We will describe the implementation for SELECT NAME, TO_CHAR(BIRTH_DATE, that do the excel work writing directly the first one, and for the other we’ll just ‘MM/DD/YYYY HH:MI’) AS BIRTH in the binary format (not html tables tell you how to use it. FROM CUSTOMER. that the program will have to convert later). AutoXlsReport_simple function. Then you’ll have to provide an array like this: array(“NAME”, “BIRTH”). Refer to Figure 3 (How To Obtain Refer to Figure four (4). Biffwriter). (We didn’t develop a complete SQL Figure four (4) shows the code for the parser, we made a simple library. So Please check the site and the license autoXlsReport_simple function. this is the simplest and easiest way to issues. manage these cases). This function receives the following We will provide you a library that will parameters: Lines from 153 to 158 interact with these two products, but you will have to download the $usrDB -> Lines from 153 to 158 do a little parse Biffwriter from its correspondent site. This is a database instance. It could be work taking the columns names from any kind of supported database. It must the query. First we will use the biffwriter from come already initialized. Christian Novak. If the user provides an array then the $report_name -> function will use it instead of the column The biffwriter provides a class that A string with a meaningful description of list in the SELECT statement. produces the excel spread sheet. We the report. will use the following methods in our Lines from 164 to 170 library: $query_string-> The SQL query for the report. Must be a Lines from 164 to 170 create a new Refer To Figure 3. simple SELECT query. biffwriter and give it a default style.

Teaching how to use the Biffwriter $column_names_array-> Line 172 class is beyond the scope of this An array containing the header of the article, I just will describe briefly the columns, this parameter is optional. Line 172 executes the query. methods while we use it in conjunction with the common If you don’t provide it, then the function Line 175 database library. will use the column’s name. Line 175 prints the headers for the You don’t even have to understand it $array_data -> columns. in order to use the functions that we’ll This is list of the columns from the SELECT provide you. statement that will appear in the report. Line 178

AutoXlsReport This parameter is also optional. Line 178 executes a while loop that prints each column from the query into We have written a small library called It’s necessary if you use database the report. autoXlsReport. We defined two main functions in your query. CCS Developer Page 10

The CodeCharge-PHP Common Database Interface. Using It Language: .PHP Database: Any To Produce MS-EXCEL Reports

Figure 4 – autoXLSReport_Simple Function

Line 182 Figure 5 – Example SQL Statement SELECT Line 182 finishes the work and sends EMPLOYEE.EMPLOYEE_ID, the report to the client. EMPLOYEE.NAME, ACTIVE.CODE, AutoXlsReport_fliped ACTIVE.DESCRIPTION FROM Sometimes, your customers could want EMPLOYEE, ACTIVE to have their reports in a different way WHERE than it’s naturally generated. ACTIVE.EMPLOYEE_ID = EMPLOYEE.EMPLOYEE_ID ORDER BY It happens very often with a master- EMPLOYEE.EMPLOYEE.ID, ACTIVE.CODE detail report.

Let’s say that you have two tables with a master-detail relationship: Figure 6 – Sample Report EMPLOYEE and ACTIVE. EMPLOYEE_ID NAME CODE DESCRIPTION 001 James S. 4154 PC Let’s say that all the employees have at 001 James S. 4157 Desktop least one employee assigned but no 001 James S. 4500 Palm computer more than twenty. 002 Claudia W. 5000 Desk 002 Claudia W. 5002 Chair If you do a simple select statement like that shown in Figure 5 - then you will have a report similar to that shown in Figure 7 – Sample Report #2 figure six (6). EMPLOYEE_ID NAME ACTIVE1 ACTIVE2 … ACTIVE20 001 James S. 4154 PC 4157 Desktop … But your costumers could want it in a 002 Claudia W. 5000 Desk 5002 Chair more readable form, similar to that CCS Developer Page 11

The CodeCharge-PHP Common Database Interface. Using It Language: .PHP Database: Any To Produce MS-EXCEL Reports

shown in figure seven (7). Figure 8 Creating The Reports Page record_events.php page.

Actually it’s the same report, it looks Explanation different but it’s just a matter of view. First we make the properly include The autoXlsReport_simple takes this of the autoXlsReport file. master-detail report and flips it into a readable view. Then we declare the global $DBTEST (your database instance) It takes the following arguments: that's already created for this page.

$usrDB -> Then we construct the columns The database instance array with a fast query to the data dictionary. $report_name -> A string with a meaningful description After that we declare a simple of the report. just one button and a listbox called query: SELECT * FROM tableName. $tableName”, we just call the $query_string -> autoXlsReport function with the The SQL query. We set its datasource to a simple database instance, the title, the DataDictionary query: query, and the columns array. $pk -> It’s the primary key column. “SELECT TABLE_NAME FROM USER_TABLES” Don't forget to place the biffwriter files and the It’s necessary in order to associate (Yes, you guessed it! It returns all of the autoXlsReport.php file in your each detail to its master. tables from the current user), and we set its publishing directory in order to databound and datatext columns to get page working. In the example above the value TABLE_NAME. should be EMPLOYEE_ID This example allows the user to We also add a little text to the form obtain all of the data for any Table $index_fliped_data -> definition for the record: on the SCHEMA. The ordinal index from where the detail data starts.

the possibilities and the general template that you should follow to In the example above it should be the On the afterInitialize event of the page (just create fast and simple report pages. number 2 (starting from the active’s after the security stuff) we add the code code) shown in Figure ten (10) to the AfterInitialize event of the page. $column_names_array , $data_array -> The tableReport function takes the The same meanings than in the tableName and creates the report. simple report. Refer to Figure eleven (11) to see the code Integrating the library with your that needs to be plugged into the CodeCharge Project

We'll just add one page to an existing Figure 9 project.

Also, for this example we want to show how you could combine the use of the Common Database interface with our AutoXlsReport library and some data dictionary stuff (Oracle).

This is just an example to guide you and show you what's possible.

You can rearrange everything to fulfill your needs.

First we create a new page called “reports” – Figure eight (8).

We create a simple recordSet, with

CCS Developer Page 12

The CodeCharge-PHP Common Database Interface. Using It Language: .PHP Database: Any To Produce MS-EXCEL Reports

Figure 10 – Page After Initialize Event About Fernando Sibaja-Araya //Custom Code @8-A43F7AC2 // ------Mr. Sibaja is a graduate computer global $reports; engineer from ITCR (Instituto Techologico de Costa Rica), and if(CCGetFromGet("REPORT")=="YES" && CCGetFromPost("TABLE_NAME")){ develops data driven web applications using CodeCharge Studio, PHP, oracle tableReport(CCGetFromPost("TABLE_NAME")); and ProgressSQL. exit(); Please send your comments } or suggestions to [email protected] // ------//End Custom Code

Figure 11 – Report_Events Code Costa Rica //put this code in your report_events.php page include("autoxlsreport.php"); function tableReport($tableName){ Jobs Board global $DBTEST; //already created Coming 2nd Week Of November!

$queryCols = "SELECT COLUMN_NAME ". DataObjx Jobs Board "FROM USER_TAB_COLUMNS ". "WHERE TABLE_NAME= '$tableName'"; Based on – but better than the Jobs Board located on DataObjx, this Jobs $DBTEST->query($queryCols); Board allows for any type of occupation, job or project to be $columns = array(); advertised.

while($DBTEST->next_record()){ Document Manager Pro $columns[] = $DBTEST->f("COLUMN_NAME"); } DataObjx will also be launching $DBTEST->close(); Document Manager Pro. This is a completely branded documents $query= "SELECT * FROM $tableName"; management system with enhanced $title = "Report of $tableName"; functionality.

autoXlsReport_simple($DBTEST, $title, $query, $columns, $columns); More about Document Manager Pro Soon!

}

Create An Application To Sell On The CCS Marketplace

Figure 12 – Retrieving Document.xls Get Ready

The CCS Marketplace is an on-line store where you can buy and sell CCS Project files or applications.

Maybe you already have a product or you have an idea for a product that you can sell on-line.

Either way, start polishing up that application to sell on the CCS Marketplace.

We’ll notify you when the CCS Marketplace goes On-Line during the 2nd week of November.

CCS Developer Page 13

Building A Document Management System Language: .ASP FEATURED ARTICLE: Part 3 of a three part series…

In our last issue, we continued building up. saves it to the our document management system. DocumentManager_CheckInOut Adding Check-Out Capability table. We worked through some fairly difficult segments of code, and in this issue – we If you recall, we mentioned in an earlier Alternatively, you could cause the increase that complexity by adding article that the ability to download a file application to perform the same additional capabilities. is different from the ability to “Check- action when the file is checked in. Out” a file. In building such applications you face We have chosen to perform this ever-increasing degrees of difficulty at action at the time the document is virtually every level. If your design is Non-CCS-File checked out for reasons that will be right, the difficulties – though still there, Using FrontPage or your favorite HTML explained below. are less difficult than they would have editor, open and refer also to the file been if you didn’t have a good design. “checkoutdownload.asp”. But, going back to our example - there are now two (2) copies of the It’s difficult to say when you have a same document in the database. good design. But, when you usually When you download a file, you’re doing One (1) copy is the one seen in the know it when you go to implement just that. Downloading it. But when grid, and the 2nd copy is the one additional features and they fit like they you’re Checking Out a file, you’re telling located in the were planned. everybody else that has access to the DocumentManager_CheckInOut file that you have downloaded it for table. Actually, they were planned. We told editing. you that from the beginning - You might think that strange, but – remember? Therefore, when you check out a there’s a reason to this madness. document – no one else should be able So let’s get on with it, shall we? to Check Out the document for editing. By making a copy of the file when the file is being checked out, we’ve What we need to do next… The routines are virtually the same as effectively maintained an ‘audit that for downloading the file, but in trail’ of who edited the document. We have implemented the ability to order to track who has the file, we need Should anything happen to the upload and download files. But we still to track additional information such as, document being shown in the Grid, need to create the ability for a user to when they checked the file out, who we still have a copy that can be check out a file, check in a file and checked out the file, etc. ‘rolled back’. perhaps, un-do a check out on a file. In order to do this we need to create Let’s say for example, that you did By combining these additional another table which we will call: not do this… make a copy, that is. capabilities and adding a bit of logic to “DocumentManager_CheckInOut” it, we can begin to see a semblance of A user checks out what the application is capable of. Refer To Figure 1. “MainDocument1.doc” and makes modifications to it. Before We Begin This table has a number of additional fields that appear (in some cases) to When they go to upload the file We’ve added a field to the Users table resemble the structure of (Check-In the file), they called: DocumentManager_Upload. accidentally upload “DocumentManager_CanAddFile” “MainDocument3.doc” – and that document overwrites the original This is a yes/no/bit field and you will Non-CCS-File “MainDocument1.doc” in the record. need to add this field to your users table Using FrontPage or your favorite HTML for the code to work. editor, refer to: Oops! Function BackUpDocument() We added this field because within in the file “checkoutdownload.asp”. This is easily corrected however, organizations – not everyone is going to because all the user needs to do is be given access to the application. Check Out the file again, and upload the correct file. Therefore, by adding this field to the Why some of the ‘Upload‘ fields users record and setting it to True, duplicated? But what if the correct file we’re effectively telling the application (“MainDocument1.doc edited that this user has DocumentManager Indeed, some of the fields do resemble version) was corrupted at some privileges. those found in table point on the users hard disk or DocumentManager_Upload. The reason floppy disk. Add this field and set the value to True for this has more to do with the logic of for the appropriate users before the application than not. Here’s where our methodology pays continuing… off. Since the original uncorrupted Let’s Consider The Logic version of “MainDocuement1.doc” is Also, we are assuming that you had all intact within the of the connection string issue sorted out When a user checks out a document, “DocumentManager_CheckInOut” since #2 and therefore, assume that the application automatically makes a table, this record can used to your connection string is properly set copy of the file being “Checked Out” and overwrite (and therefore correct the CCS Developer Page 14 Building A Document Management System Part 1 of a three part series, continued…

Figure 1 - DocumentManager_CheckInOut problem in this case) the corrupted Refer also to the other version 2 of the .doc file. Admittedly, article in this issue it’s the earliest good version and version 2 has to be re-keyed, but... “Expanding The CodeCharge Studio But you can see now why we’ve Portal – Part 2” that chosen this method. It’s safe. explains a method for

Adding Check-In Capability creating links dynamically based on the name of the page that Non-CCS-File the user is viewing. Using FrontPage or your favorite HTML editor, open and refer also to the file “checkinUpload.asp”. YOUR ADVERTISEMENT HERE Providing the “Check-In” capability is Advertise Your Site Or similar to the performing the original Product upload routine. Advertise your web-site or In fact, since we caused the ‘history’ Figure 2 – Table: DocumentManager_Upload product in our next issue. and a copy of the file to be saved at _To Users the time the file was checked out, the You’ve gone to a lot of trouble only thing happening here is a to create a cool web site or replication of the upload/overwrite perhaps you’ve build a routines. commercial application using CodeCharge Studio. Adding Un-Do Check-Out Capability Advertise it here in our next issue.

Non-CCS-File Using FrontPage or your favorite HTML editor, open and refer also to the file “undoCheckin.asp”. • Un-Do a Check-Out on a file representing the options a given user can take against a give file are The ability to “Un-Do” you Check Out We need to provide the application with defined by the bit flags and associated is important. the ability to discern what actions any with the user via the given user can take against a given file. DocumentManager_Upload_To_Users Sometimes users will inadvertently table. check out a file only to realize Therefore, we need to modify the table Since we cannot dynamically alter the moments later when they open the DocumentManager_Upload_To_Users to URL reference when a link has been file, that it the wrong one. account for the various actions that a defined as a “Form Link Control”, we given user can take when they are need to use a “Form label control” Sometimes they intended to download assigned access to the file. instead. the file and clicked the “Check-Out” link instead and on realizing this want Refer to Figure 2. In order to understand this better, to correct their action. open the Feel free to include additional options as “DocumentManagerFiles_list.ccp” file Since undoing a check out means that business requirements dictate. and perform a right-click, show code no change will occur to the current on {lblCheckInOut}. document, we simply need to delete These ‘attributes’ are important because the record located within table they allow us to dynamically create or not This code demonstrates one method “DocumentManager_CheckInOut” create the links necessary to perform a that can be used to produce a containing the copy made earlier given task. hyperlink, dynamically. That is to when the user inadvertently checked say, display an icon or don’t – for any out the document. In other words, they control the ‘option’ given user/for any given file. icons that the user sees to the left of the Setting Document Level User document/file record. Ultimately, once you have the Permissions variables available to you, the rest is Controlling The Icons/Options For A logic. Now that we’ve added the ability to; Document • Check-Out a file, Look at the routine located in the • Check-In a file and As mentioned earlier, the Icons “DocumentManagerUpload_lblCheckIn CCS Developer Page 13 Building A Document Management System Part 1 of a three part series, continued…

Out_BeforeShow()” event. Next Steps… here and how you apply it – is up to you. Notice that the icon either appears or There you have it. The core doesn’t depending on the bit flag functionality that is required to The flow of the application may associated with the user for this empower you with the minimum change according to the needs of document. capabilities that any document your organization. management system requires. Associating Content Type With An Icon Where you take this technology from

Open the CCS file “DocumentManagerFiles_List.asp” and refer to the function called; Figure 3 – Refreshing/Reloading The Screen “DocumentManagerUpload_lblContent common. button) that the screen automatically button…