Post on 08-Dec-2016
transcript
Developer's Guide
c-treeACE SQL PHP
Copyright Notice
Copyright © 1992-2017 FairCom Corporation. All rights reserved. No part of this publication may be stored in a retrieval
system, or transmitted in any form or by any means, electronic, mechanical, photocopying, recording or otherwise without
the prior written permission of FairCom Corporation. Printed in the United States of America.
Information in this document is subject to change without notice.
Trademarks
c-treeACE, c-treeRTG, c-treeAMS, c-tree Plus, c-tree, r-tree, FairCom and FairCom’s circular disc logo are trademarks of
FairCom, registered in the United States and other countries.
The following are third-party trademarks: AMD and AMD Opteron are trademarks of Advanced Micro Devices, Inc.
Macintosh, Mac, Mac OS, and Xcode are trademarks of Apple Inc., registered in the U.S. and other countries.
Embarcadero, the Embarcadero Technologies logos and all other Embarcadero Technologies product or service names
are trademarks, service marks, and/or registered trademarks of Embarcadero Technologies, Inc. and are protected by the
laws of the United States and other countries. Business Objects and the Business Objects logo, BusinessObjects, Crystal
Reports, Crystal Decisions, Web Intelligence, Xcelsius, and other Business Objects products and services mentioned
herein as well as their respective logos are trademarks or registered trademarks of Business Objects Software Ltd.
Business Objects is an SAP company. HP and HP-UX are registered trademarks of the Hewlett-Packard Company. AIX,
IBM, POWER6, POWER7, and pSeries are trademarks or registered trademarks of International Business Machines
Corporation in the United States, other countries, or both. Intel, Intel Core, Itanium, Pentium and Xeon are trademarks or
registered trademarks of Intel Corporation or its subsidiaries in the United States and other countries. Microsoft, the .NET
logo, the Windows logo, Access, Excel, SQL Server, Visual Basic, Visual C++, Visual C#, Visual Studio, Windows,
Windows Server, and Windows Vista are either registered trademarks or trademarks of Microsoft Corporation in the
United States and/or other countries. Novell and SUSE are registered trademarks of Novell, Inc. in the United States and
other countries. Oracle and Java are registered trademarks of Oracle and/or its affiliates. QNX and Neutrino are
registered trademarks of QNX Software Systems Ltd. in certain jurisdictions. CentOS, Red Hat, and the Shadow Man logo
are registered trademarks of Red Hat, Inc. in the United States and other countries, used with permission. UNIX and
UnixWare are registered trademarks of The Open Group in the United States and other countries. Linux is a trademark of
Linus Torvalds in the United States, other countries, or both. Python and PyCon are trademarks or registered trademarks
of the Python Software Foundation. OpenServer is a trademark or registered trademark of Xinuos, Inc. in the U.S.A. and
other countries. Unicode and the Unicode Logo are registered trademarks of Unicode, Inc. in the United States and other
countries.
Btrieve is a registered trademark of Actian Corporation.
ACUCOBOL-GT, MICRO FOCUS, RM/COBOL, and Visual COBOL are trademarks or registered trademarks of Micro
Focus (IP) Limited or its subsidiaries in the United Kingdom, United States and other countries.
isCOBOL and Veryant are trademarks or registered trademarks of Veryant in the United States and other countries.
All other trademarks, trade names, company names, product names, and registered trademarks are the property of their
respective holders.
Portions Copyright © 1991-2016 Unicode, Inc. All rights reserved.
Portions Copyright © 1998-2016 The OpenSSL Project. All rights reserved. This product includes software developed by
the OpenSSL Project for use in the OpenSSL Toolkit (http://www.openssl.org/).
Portions Copyright © 1995-1998 Eric Young (eay@cryptsoft.com). All rights reserved. This product includes cryptographic
software written by Eric Young (eay@cryptsoft.com). This product includes software written by Tim Hudson
(tjh@cryptsoft.com).
Portions © 1987-2017 Dharma Systems, Inc. All rights reserved. This software or web site utilizes or contains material
that is © 1994-2007 DUNDAS DATA VISUALIZATION, INC. and its licensors, all rights reserved.
Portions Copyright © 1995-2013 Jean-loup Gailly and Mark Adler.
12/13/2017
All Rights Reserved iii www.faircom.com
Contents
1. c-treePHP for c-treeACE SQL ............................................................................ 1
2. Quick Start .......................................................................................................... 3
2.1 Using PHP on Windows ....................................................................................... 6
Packages Required for Windows ........................................................................................ 6
Install Microsoft IIS .............................................................................................................. 7
Install PHP .......................................................................................................................... 9
Configure Microsoft IIS ..................................................................................................... 10
2.2 Using PHP on Linux and Unix ............................................................................ 13
Install unixODBC ............................................................................................................... 13
Install PHP ........................................................................................................................ 14
Install the Web Server ....................................................................................................... 15
2.3 Install and Execute the ODBC Tutorials ............................................................. 16
Run the ODBC Tutorials with IIS on Windows .................................................................. 16
Run the ODBC Tutorials with Apache on Linux/Unix ........................................................ 21
3. Using PHP with the sql.php API ...................................................................... 23
3.1 Using the sql.php API on Windows .................................................................... 24
Configure the sql.php Extension ....................................................................................... 24
Compile the sql.php Extension ......................................................................................... 27
Run the sql.php Tutorials with Microsoft IIS ..................................................................... 29
3.2 Using the sql.php API on Linux and Unix ........................................................... 31
Configure PHP .................................................................................................................. 31
Compile the sql.php Extension (Linux/Unix) ..................................................................... 33
Run the sql.php Tutorials with Linux/Unix Apache ........................................................... 34
4. Introductory Tutorial ........................................................................................ 37
4.1 Init ...................................................................................................................... 38
4.2 Define ................................................................................................................ 39
4.3 Manage .............................................................................................................. 40
4.4 Done .................................................................................................................. 42
4.5 Additional Resources ......................................................................................... 43
5. Relationships ................................................................................................... 44
5.1 Init ...................................................................................................................... 46
5.2 Define ................................................................................................................ 47
5.3 Manage .............................................................................................................. 50
c-treePHP for c-treeACE SQL
All Rights Reserved iv www.faircom.com
5.4 Done .................................................................................................................. 54
5.5 Additional Resources ......................................................................................... 55
6. Record/Row Locking ....................................................................................... 56
6.1 Init ...................................................................................................................... 58
6.2 Define ................................................................................................................ 59
6.3 Manage .............................................................................................................. 60
6.4 Done .................................................................................................................. 63
6.5 Additional Resources ......................................................................................... 64
7. Transaction Processing .................................................................................. 65
7.1 Init ...................................................................................................................... 67
7.2 Define ................................................................................................................ 68
7.3 Manage .............................................................................................................. 70
7.4 Done .................................................................................................................. 75
7.5 Additional Resources ......................................................................................... 76
8. Additional Functionality .................................................................................. 77
9. c-treePHP Functions ........................................................................................ 78
9.1 Resource Types ................................................................................................. 78
9.2 c-treePHP Example ........................................................................................... 79
10. Index ............................................................................................................... 100
FairCom Typographical Conventions
Before you begin using this guide, be sure to review the relevant terms and typographical
conventions used in the documentation.
The following formatted items identify special information.
Formatting convention Type of Information
Bold Used to emphasize a point or for variable expressions such as parameters
CAPITALS Names of keys on the keyboard. For example, SHIFT, CTRL, or ALT+F4
FairCom Terminology FairCom technology term
FunctionName() c-treeACE Function name
Parameter c-treeACE Function Parameter
Code Example Code example or Command line usage
utility c-treeACE executable or utility
filename c-treeACE file or path name
CONFIGURATION KEYWORD c-treeACE Configuration Keyword
CTREE_ERR c-treeACE Error Code
All Rights Reserved vi www.faircom.com
All Rights Reserved 1 www.faircom.com
1. c-treePHP for c-treeACE SQL
Today’s progressive business environments demand online availability. The method of choice is
via the web and PHP has become the language of choice for dynamic web scripting.
PHP (Hypertext PreProcessor) is a widely-used general-purpose scripting language that is
especially suited for web development and can be embedded into HTML. c-treeACE SQL is a
powerful database technology offering a wide range of interfaces now including PHP support.
FairCom’s c-treeACE SQL PHP module extends your data access to the world through this
popular web interface.
c-treeACE SQL PHP Interface technology gives the means to access data from c-treeACE SQL.
c-treeACE SQL PHP modules can be installed with either Apache or Microsoft IIS (Windows) web
servers.
Accessing c-treeACE from PHP
The c-treeACE package provides two versions of the c-treeACE SQL PHP drivers, each in its
own directory:
sql.php
C:\FairCom\v11.x.x\winX64\sdk\sql.php
(If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and
replace sdk with Driver.)
These drivers support PHP 5. See C:\FairCom\v11.x.x\winX64\sdk\sql.php.pdo for PHP 7
support.
Instructions are provided for using the c-treeACE SQL ODBC interface to connect c-treeACE
to PHP. All later versions of PHP (PHP 4, PHP 5, and PHP 7) are compatible with the ODBC
interface.
Note: If you are NOT using ODBC, only PHP 5 is supported. Use the other folder, sql.php.pdo, to connect to c-treeACE using PHP 7.
c-treePHP for c-treeACE SQL
All Rights Reserved 2 www.faircom.com
sql.php.pdo
C:\FairCom\v11.x.x\winX64\sdk\sql.php.pdo - Notice the folder name is sql.php.pdo
(If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and
replace sdk with Driver.)
These drivers support PHP 7 and the PDO (PHP Data Object) extension.
This is the preferred way to access c-treeACE from PHP.
Each folder contains a ReadMe file for the drivers in that folder.
Documentation about c-treeACE SQL can be found on FairCom’s web site www.faircom.com.
All Rights Reserved 3 www.faircom.com
2. Quick Start
This Quick Start comprises four simple tutorials designed to guide you through the basic use of
the c-treeACE SQL PHP Interface technology.
This guide presents the following ways to use c-treeACE with PHP:
Using PHP 7 with the PDO Extension - This is the preferred method of connecting
c-treeACE with PHP. It supports PHP 7.
Using PHP with the sql.php API (page 23) - This method uses the native c-treeACE
sql.php driver to connect to PHP 5.x.x. It does not support later versions of PHP.
Using PHP with ODBC - This method is an alternative to connecting to PHP using the native
sql.php driver or the PDO extension.
Overview of the Tutorials
Like all other tutorials in the c-tree series, each example simplifies the concepts of database
programming into four simple steps: Initialize(), Define(), Manage(), and You're Done() !
No matter what c-treeACE Interface language you are using, FairCom follows this same
high-level flow in all tutorials. This makes it easy for developers to "cross-over" from one
language interface to another as these basic concepts apply to all.
Initialize()
Every language requires some form of initial "logon" or "connection" procedure to establish a session with the database. This is done in the Initialize() stage of the program.
Define()
Database definitions (DDL), Table/File schema definitions, Index definitions, Table/File creation, and Table/File open operations are all addressed in the Define() stage of the program.
Manage()
This stage of the program is where the database is operated on, as in managing your data. Adding/Reading/Updating/Deleting records/rows are handled in this stage of the program.
Done()
When the program ends, the database session should be closed. This stage handles the necessities to "de-init", by closing Tables/Files and issuing any required "logoff" or "disconnect" type procedures.
Presented here are tutorials that follow the "Initialize(), Define(), Manage(), and You're Done() ! "
approach.
The source code is located in:
Quick Start
All Rights Reserved 4 www.faircom.com
C:\FairCom\V*\<platform>\sdk\sql.php\tutorials
(where C:\FairCom.VX.X.X is your installation directory. The default installation directory is
C:\FairCom\V*).
Note: If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG,
and replace sdk with Driver.
Overview of the Tutorials
Here is a conceptual overview of what these tutorials do:
Tutorial #1: Introductory - Simple Single Table
We wanted to keep this program as simple as possible. This program does the following:
Initialize() - Connects to the c-treeACE database engine.
Define() - Defines and creates a "customer master" (custmast) file/table.
Manage() - Adds a few records/rows; Reads the records/rows back from the database and
displays their content; and then deletes the records/rows.
Done() - Disconnects from c-treeACE Database Engine.
Tutorial #2: Relational Model and Indexing
Here we now add a bit more complexity, introducing multiple tables, with related indices in order
to form a simple "relational" database simulating an Order Entry system. Here is an overview of
what will be created:
Initialize() - Connects to the c-treeACE database engine.
Define() - Defines and creates the "custmast", "custordr", "ordritem" and the "itemmast"
files/tables with related indices.
Manage() - Adds some related records/rows to all files/tables. Then queries this order
database.
Done() - Disconnects from c-treeACE Database Engine.
Quick Start
All Rights Reserved 5 www.faircom.com
Tutorial #3: Locking
Here we demonstrate the enforcement of data integrity by introducing record/row "locking".
Initialize() - Connects to the c-treeACE database engine.
Define() - Defines and creates a "customer master" (custmast) file/table.
Manage() - Adds a few records/rows; Reads the records/rows back from the database and
displays their content. Then demonstrates an update operation under locking control, and a
scenario that shows a locking conflict.
Done() - Disconnects from c-treeACE database engine.
Tutorial #4: Transaction Processing
Here we demonstrate transaction control.
Initialize() - Connects to the c-treeACE database engine.
Define() - Defines and creates our four file/tables.
Manage() - Adds records/rows to multiple tables under transaction control.
Done() - Disconnects from c-treeACE Database Engine.
Use the help file navigation arrows at the top of your browser to progress through the
tutorials.
Feel free to use these projects as a starting point for your next c-treeACE project!
Quick Start
All Rights Reserved 6 www.faircom.com
2.1 Using PHP on Windows
To use the PHP IIS server extensions, install PHP on your computer and use the c-treeACE SQL
ODBC interface to connect PHP to c-tree. All recent versions of PHP (PHP 4, PHP 5, and PHP 7)
will work using ODBC.
Note: If you chose to integrate using the c-treeACE SQL PHP API instead of ODBC, only PHP 5 can be used.
Packages Required for Windows
To install and execute the c-treeACE SQL PHP tutorials with Microsoft IIS, you will need to install
Internet Information Service (IIS) and PHP, as described in the following sections:
Install IIS (page 7)
Install PHP (page 9)
Configure IIS (page 10)
Note: PHP 7 requires the c-treeACE SQL ODBC interface.
Quick Start
All Rights Reserved 7 www.faircom.com
Install Microsoft IIS
To install Internet Information Service (IIS) web server on Microsoft Windows, follow these
instructions:
Note: This section shows typical procedures using Windows 7 as an example. Some of the dialog and labels may look different in other versions of Windows.
1. Open the Windows Control Panel (Usually Start Menu > Control Panel) and select Programs:
2. In the program menu, select Turn Windows features on and off:
Quick Start
All Rights Reserved 8 www.faircom.com
3. Wait for the content of the Windows Features window to appear and check Internet Information Services.
4. Expand Internet Information Services > World Wide Web Services > Application Development Features and check CGI:
5. Click OK to begin the installation of IIS.
Quick Start
All Rights Reserved 9 www.faircom.com
Install PHP
This section explains how to install the PHP extensions for IIS. These procedures can be used
with all recent versions of PHP: PHP 4, PHP 5, and PHP 7.
1. Open your web browser and go to http://www.php.net/downloads.php http://www.php.net/downloads.php and download the Windows Binaries zip package for the latest PHP version:
2. Once you have downloaded the file, right-click it, select Extract All, enter C:\php as the destination, and click Extract:
Quick Start
All Rights Reserved 10 www.faircom.com
Configure Microsoft IIS
To configure IIS for PHP, follow these steps:
Note: This section shows typical procedures using Windows 7 as an example. Some of the dialog
and labels may look different in other versions of Windows.
1. Open the Start Menu, select Run, and execute InetMgr.exe:
2. In the InetMgr main window, double-click Handler Mappings:
3. In the Handler Mappings window, click Add Module Mapping... on the right-side Actions menu:
Quick Start
All Rights Reserved 11 www.faircom.com
4. Complete the dialog window with the following: Request Path: *.php Module: FastCgiModule Executable: C:\php\php-cgi.exe Name: PHP
5. Click OK and then Yes on the "Add Script Map" message box that appears. Finally, close the InetMgr dialog.
6. Restart your computer to ensure everything is configured.
Quick Start
All Rights Reserved 12 www.faircom.com
Note: It is not mandatory to restart your computer at this time, however, it is advised to ensure IIS is properly configured.
Quick Start
All Rights Reserved 13 www.faircom.com
2.2 Using PHP on Linux and Unix
To install and execute c-treeACE SQL PHP tutorials on Linux/Unix, please consider using the
package manager of the platform to avoid system settings errors.
In this section we list the commands using the Linux Ubuntu as an example. The commands
described here may vary depending on your environment.
You will need to install ODBC, PHP 5.x.x, and the Apache web server as described in the
following sections:
Install unixODBC (page 13)
Install PHP (page 14)
Install the Web Server (page 15)
Install unixODBC
To install the ODBC on Linux you must use your package manager on Linux:
sudo apt install unixodbc
Once you complete the installation on your environment, set the c-treeACE SQL ODBC Driver as
described in the FairCom ODBC Driver Guide in the topic titled Unix/Linux ODBC Managers
http://docs.faircom.com/doc/odbc/#59603.htm.
In our example the odbcinst.ini is:
[ctreeSQL]
Driver=/usr/lib/odbc/libctodbc.so
Description=ODBC for ctreeSQL
Host=localhost
Database=ctreeSQL
The odbc.ini is:
[c-treeACE ODBC Driver]
Driver=ctreeSQL
Host=localhost
Database=ctreeSQL
User ID=ADMIN
Password=ADMIN
Service=6597
Description=ODBC for ctreeSQL
To allow the unixODBC install the odbcinst and odcini you must execute the following commands:
odbcinst -i -d -f /etc/odbcinst.ini
odbcinst -i -s -l -f /etc/odbc.ini
You can test if your DSN is installed by executing:
odbcinst -s –q
Result: [c-treeACE ODBC Driver]
Please consider to set ODBCINI on environment variables:
export ODBCINI=/etc/odbc.ini
Quick Start
All Rights Reserved 14 www.faircom.com
Now you can check if you unixODBC is configured for c-tree by running a tool connected to a
unixODBC data source. For example, you can execute the Interactive SQL (isql) from /usr/bin as
shown below:
Install PHP
PHP is included in many common Linux and Unix distributions. If it is not installed, it is best to
install PHP on your system using the package manager, for example:
sudo apt install php php-odbc
sudo apt install php-fpm
To configure FastCGI, type the following command (this example uses the nano text editor):
sudo nano /etc/php/7.0/fpm/php.ini
Edit the php.ini file to find:
cgi.fix_pathinfo
And set it to:
cgi.fix_pathinfo=0
To restart the service:
sudo service php7.0-fpm restart
Note: PHP 4, PHP 5, or PHP 7 will work with the c-treeACE SQL ODBC interface. The c-treeACE SQL PHP interface that is integrated with c-tree only supports PHP 5.
Quick Start
All Rights Reserved 15 www.faircom.com
Install the Web Server
You must install the web server you wish to use with PHP. For example, to install the NGINX web
server:
sudo apt install nginx
Copy the FairCom tutorials to the folder: /var/www/html
Configure the web server to run PHP fastCGI:
sudo nano /etc/nginx/sites-available/default
In the text editor, find the following:
location ~ \.php$ {
The lines below it provide examples of fastCGI configurations. Delete comment character “#”
from the appropriate line to allow fastcgi_pass to be used, as shown below:
Restart the web server as follows:
sudo service nginx restart
Quick Start
All Rights Reserved 16 www.faircom.com
2.3 Install and Execute the ODBC Tutorials
To execute the c-treeACE SQL PHP tutorials with ODBC, be sure to have installed and
configured the c-treeACE SQL ODBC driver. Below is an example of a configured driver on the
Windows platform:
Run the ODBC Tutorials with IIS on Windows
Before you can execute the c-treeACE SQL PHP ODBC tutorials on Windows, first copy the
tutorials files into the IIS root directory as shown below:
1. Open an Administrator Command Prompt and move to C:\inetpub\wwwroot and copy the contents of your installation directory. For example, if you installed release V11 in the default Windows location, the directory would be C:\FairCom\V*\sdk\sql.php. (If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and replace sdk with Driver.)
2. To check if your PHP is working with c-treeACE on ODBC you can directly run it from command line. This may help you to identify configuration issues better than executing PHP from a web server because a web server may not show the complete error information. To execute PHP from a command line, go to the C:\php folder then execute:
php C:\inetpub\wwwroot\PHP_Tutorial1_ODBC.php
Quick Start
All Rights Reserved 17 www.faircom.com
3. Now you are done and can use your favorite web browser to execute the tutorials by
connecting to http://localhost. For example localhost/PHP_Tutorial1_ODBC.php
should appear as shown below:
Quick Start
All Rights Reserved 18 www.faircom.com
localhost/PHP_Tutorial2_ODBC.php:
Quick Start
All Rights Reserved 19 www.faircom.com
localhost/PHP_Tutorial3_ODBC.php:
Quick Start
All Rights Reserved 20 www.faircom.com
localhost/PHP_Tutorial4_ODBC.php:
The source code for these tutorials is contained in the files you copied to the server root in step 1:
PHP_Tutorial1_ODBC.php
PHP_Tutorial2_ODBC.php
PHP_Tutorial3_ODBC.php
PHP_Tutorial4_ODBC.php
The contents of these files corresponds to the tutorials for the c-treeACE sql.php API
(PHP_Tutorial1.php, PHP_Tutorial2.php, PHP_Tutorial3.php, PHP_Tutorial4.php). Both the
sql.php API and the ODBC tutorials share the same basic structure of Initialize(), Define(),
Manage(), and You’re Done(), as described later in this guide.
Quick Start
All Rights Reserved 21 www.faircom.com
Run the ODBC Tutorials with Apache on Linux/Unix
To execute the PHP tutorials with ODBC on a Unix/Linux platform, be sure you have installed the
unixODBC c-treeACE driver.
Once you have PHP installed and web server configured to run your PHP script (e.g. NGINX with
FastCGI), all you need to do is to copy the PHP tutorial files into the web server folder. For
example, the NGINX server uses /var/www/html/.
To check if your PHP is working with c-treeACE using ODBC, you can directly run it from
command line. This may help you to identify configuration issues better than executing PHP from
the web server, which may not provide complete error information. To test from a command line,
type the following at a command prompt:
Quick Start
All Rights Reserved 22 www.faircom.com
php /var/www/html/PHP_Tutorial1_ODBC.php
Now you are ready to start using your favorite web browser to experiment with the tutorials. Point
your browser to each of the following URLs (the results should look similar to the Windows output
shown in the previous section):
localhost/PHP_Tutorial1_ODBC.php
localhost/PHP_Tutorial2_ODBC.php
localhost/PHP_Tutorial3_ODBC.php
localhost/PHP_Tutorial4_ODBC.php
The source code for these tutorials is contained in the files listed above. The contents of these
files corresponds to the tutorials for the c-treeACE sql.php API (PHP_Tutorial1.php,
PHP_Tutorial2.php, PHP_Tutorial3.php, PHP_Tutorial4.php). Both the sql.php API and the
ODBC tutorials share the basic structure of Initialize(), Define(), Manage(), and You’re Done(), as
described later in this guide.
All Rights Reserved 23 www.faircom.com
3. Using PHP with the sql.php API
The sql.php API supplied with c-treeACE is a native PHP API designed specifically for interfacing
c-treeACE with PHP 5.x.x. It does not support later versions of PHP.
The sql.php API is provided primarily for environments that cannot use the PDO extension or
ODBC (e.g., Unix/Linux systems running PHP 5.x.x. where you are unable to install an ODBC
driver).
The preferred method of interfacing c-treeACE with PHP is to use the PDO extension, which
supports all recent versions of PHP. See Using PHP 7 with the PDO Extension.
If you want to interface PHP 5.x.x. with c-treeACE using the sql.php API, follow the procedures in
the appropriate part of this chapter:
Using the sql.php API on Windows (page 24)
Using the sql.php API on Linux and Unix (page 31)
Like all other tutorials in the c-tree series, each example simplifies the concepts of database
programming into four simple steps: Initialize(), Define(), Manage(), and You're Done() !
No matter what c-treeACE Interface language you are using, FairCom follows this same
high-level flow in all tutorials. This makes it easy for developers to "cross-over" from one
language interface to another as these basic concepts apply to all.
Initialize()
Every language requires some form of initial "logon" or "connection" procedure to establish a session with the database. This is done in the Initialize() stage of the program.
Define()
Database definitions (DDL), Table/File schema definitions, Index definitions, Table/File creation, and Table/File open operations are all addressed in the Define() stage of the program.
Manage()
This stage of the program is where the database is operated on, as in managing your data. Adding/Reading/Updating/Deleting records/rows are handled in this stage of the program.
Done()
When the program ends, the database session should be closed. This stage handles the necessities to "de-init", by closing Tables/Files and issuing any required "logoff" or "disconnect" type procedures.
Presented here are tutorials that follow the "Initialize(), Define(), Manage(), and You're Done() ! "
approach.
Using PHP with the sql.php API
All Rights Reserved 24 www.faircom.com
3.1 Using the sql.php API on Windows
To install and execute the sql.php tutorials with Microsoft IIS, you will need to set up the sql.php
extension as described in the following sections:
Configure the sql.php Extension (page 24)
Compile the sql.php Extension (page 27)
Run the sql.php API IIS Tutorials (page 29)
Configure the sql.php Extension
To configure the c-treeACE sql.php extension, follow these steps:
1. Open an Administrator Command Prompt, move to C:\php and copy php.ini-dist to C:\Windows\php.ini
2. Open C:\Windows\php.ini with a text editor such as Notepad and search for
extension_dir= "./" and change "./" to "C:\php\ext":
Using PHP with the sql.php API
All Rights Reserved 25 www.faircom.com
3. Search for the extension list (you can search for ";extension"), add
extension=php_ctsql.dll to the end of the list, and save and close php.ini
Using PHP with the sql.php API
All Rights Reserved 26 www.faircom.com
4. Now return to your Administrator Command Prompt (if you closed it open a new one), move to C:\php\ext and copy php_ctsql.dll. (If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and replace sdk with Driver.)
Using PHP with the sql.php API
All Rights Reserved 27 www.faircom.com
Compile the sql.php Extension
To compile and install the c-treeACE sql.php extension on Windows, follow the steps in this
section.
Step 1: Build PHP
To build PHP 5 from the source code, follow the Build your own PHP on Windows
https://wiki.php.net/internals/windows/stepbystepbuild page.
When you reach the Compile section, you will need to modify the steps as shown below:
1. Copy these .h files from the c-tree include folder, <basedir>\include, to the c-tree include folder sql.embedded <basedir>\include\sdk\sql.embedded:
ct_oem.h, ctsql_lib.h, ctsqlall.h, ctsqlray.h, ctvers.h, dh_custom.h, dh_literals.h
Where <basedir> is the full path of your c-treeACE or c-treeRTG installation directory, e.g.:
C:\FairCom\V11.x.x\win32
2. Open a command prompt and enter the build directory:
cd C:\php-sdk\
3. Set up the build environment variables:
bin\phpsdk_setvars.bat
Change directory to the location of your PHP source code, e.g.:
cd C:\php-sdk\phpdev\vc12\x86\php-5.6.22-src
4. Run the following based on the FairCom product you are using:
• c-treeACE
buildconf --force --add-modules-dir=<basedir>\sdk\sql.php
Where <basedir> is the full path of your c-treeACE installation directory, e.g.:
C:\FairCom\ V11.x.x\win32
• c-treeRTG
buildconf --force --add-modules-dir=<basedir>\Driver\sql.php
Where <basedir> is the full path of your c-treeRTG installation directory
5. Enable the c-treeACE SQL PHP extension by using the --add-modules-dir switch as follows:
configure --disable-all --enable-cli --enable-cgi
--enable-object-out-dir=.. --disable-ipv6 --disable-zts
--with-ctsql=shared,<basedir>
Where <basedir> is the full path of your c-treeACE or c-treeRTG installation directory, e.g.:
C:\FairCom\V11.x.x\win32
6. Copy the OpenSSL libraries:
copy <basedir>\lib\License.Lib\openssl\"Microsoft Visual Studio
2012"\libeay32.lib <basedir>\sdk\sql.php\src\ctlibeay32.lib
copy <basedir>\lib\License.Lib\openssl\"Microsoft Visual Studio
2012"\ssleay32.lib <basedir>\sdk\sql.php\src\ctssleay32.lib
7. To build PHP, run:
nmake clean (in case you need to recompile)
nmake
8. You can now test the results as follows:
Using PHP with the sql.php API
All Rights Reserved 28 www.faircom.com
php -c php.ini -f C:\inetpub\wwwroot\PHP_Tutorial1.php >> out.html
Step 2: Install the Extension
The compilation run in step 1 will also build the c-treeACE SQL PHP extension. You can find the
extension compiled into your work\Debug_TS or work\Release_TS directory.
To install the extension, you can drag and drop the content into your installed PHP folder, e.g
C:\php, (The PHP folder must be cleared so the entire content can be copied and take effect.)
Using PHP with the sql.php API
All Rights Reserved 29 www.faircom.com
Run the sql.php Tutorials with Microsoft IIS
To install and execute the c-treeACE sql.php tutorials with Microsoft Internet Information Service
(IIS), be sure to install IIS and PHP 5.x.x as described in the previous sections. Next, you will
need to copy the tutorials files into the IIS root directory as shown in this section.
Configure the c-treeACE SQL PHP Extension
1. Open an Administrator Command Prompt, move to C:\inetpub\wwwroot, and copy the contents of your installation directory. For example, if you installed release c-treeACE V11 in the default Windows location, the directory would be C:\FairCom\V11.0.0\winX64\sdk\sql.php\tutorials. (If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and replace sdk with Driver.)
2. Open your favorite web browser and connect to http://localhost. You should see the index.htm page with hyperlinks to the three tutorials to be executed:
Using PHP with the sql.php API
All Rights Reserved 30 www.faircom.com
3. Click on the tutorial hyperlinks to execute the tutorials:
Using PHP with the sql.php API
All Rights Reserved 31 www.faircom.com
3.2 Using the sql.php API on Linux and Unix
To install and execute c-treeACE sql.php tutorials with Apache on Unix/Linux systems, you will
need to set up PHP 5.x.x as described in the following sections:
Configure PHP (page 31)
Compile the sql.php Extension (page 33)
Run the sql.php Tutorials with Linux/Unix Apache (page 34)
Configure PHP
PHP is included in many common Linux and Unix distributions. The latest version of PHP can be
downloaded from the PHP website http://www.php.net/downloads.php.
To configure PHP to run c-treeACE SQL PHP follow these steps:
1. Open php.ini with your favorite text editor. In most installations you will find php.ini in /etc/php5/apache2/php.ini.
2. Search for extension_dir.
• If this line is commented out (; on the beginning of the line) un-comment this line and
replace the contents of the quotes with your c-treeACE SQL PHP extensions directory.
• If this line is not commented, it's better for you to mve ctsql.so into your default PHP
extensions directory.
3. Search for extensions area and add extension=ctsql.so to configure the c-treeACE SQL
PHP module into your PHP:
Using PHP with the sql.php API
All Rights Reserved 32 www.faircom.com
4. Save the changes to php.ini and close your text editor.
5. From the root shell restart your web server with the following command: /etc/init.d/apache2 restart
Using PHP with the sql.php API
All Rights Reserved 33 www.faircom.com
Compile the sql.php Extension (Linux/Unix)
Requrements:
PHP4 or PHP5 development package
Perl
Autoconf
Automake
GNU m4
C++ Compiler
Step 1: Create Configuration Script
Move to /FairCom/Vx.x.x/linux.x86.32bit/sdk/sql.php/src (where /FairCom/Vx.x.x/linux.x86.32bit/
is your c-treeACE installation directory):
cd /FairCom/Vx.x.x/linux.x86.32bit/sdk/sql.php/src
(If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and
replace sdk with Driver.)
Run the phpize command to create configuration script:
phpize
Step 2: Configure and Build
Run the configure script to create the makefile containing the instructions to build the c-treeACE
SQL PHP extension:
./configure
Build c-treeACE SQL PHP extension using make:
make
Step 3: Install (Optional)
If you want to install the c-treeACE SQL PHP extension into your PHP installation extensions
directory, run make install as root user.
Switch to root user:
su
[Enter your root password]
Run the installer:
make install
Note: If you install using make install make sure php.ini is configured to load extensions from the PHP installation extensions directory.
Using PHP with the sql.php API
All Rights Reserved 34 www.faircom.com
Note: If you have a configure script with installed Autotools, follow these steps: > libtoolize > aclocal > autoreconf -i > phpize > ./configure --make-ctsql
Run the sql.php Tutorials with Linux/Unix Apache
To execute the c-treeACE sql.php PHP tutorials, copy the tutorials files into a directory accessible
to your web server (here we use the web server root directory) as shown below:
1. Open a root shell and move to /var/www/ and copy the contents of /FairCom/V10.0.0/<platform>/sdk/sql.php/tutorials/ (where /FairCom/VX.X.X/ is your installation directory):
debian:~# cd /var/www/
debian:/var/www# cp -v
/FairCom/V10.0.0/linux.x86.32bit/sdk/sql.php/tutorials/* .
(If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and
replace sdk with Driver.)
Using PHP with the sql.php API
All Rights Reserved 35 www.faircom.com
2. Make sure c-treeACE SQL is running.
3. Open your favorite web browser and connect to http://localhost/index.htm (make sure you are using a proper URL if you did not use the web server root directory). You should see the index.htm page with hyperlinks to the three tutorials to be executed:
4. Click the tutorials hyperlinks to execute the tutorials:
Using PHP with the sql.php API
All Rights Reserved 36 www.faircom.com
Introductory Tutorial
All Rights Reserved 37 www.faircom.com
4. Introductory Tutorial
..\sdk\sql.php\tutorials\PHP_Tutorial1.php
If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and replace
sdk with Driver.
This tutorial will take you through the basic use of the c-treeACE SQL PHP Interface.
Like all other examples in the c-tree tutorial series, this tutorial simplifies the creation and use of a
database into four simple steps: Initialize(), Define(), Manage(), and You’re Done() !
Note: The code shown in this section if found in the version of the tutorial that uses the c-treeACE sql.php API. If you are using the c-treeACE SQL ODBC API to interface with PHP, the general flow of the tutorial will be the same, but the specifics will differ in some places due to the differences between sql.php and ODBC. Consult the source code for the specific version of the tutorial you are using for the exact coding techniques.
Tutorial #1: Introductory - Simple Single Table
We wanted to keep this program as simple as possible. This program does the following:
Initialize() - Connects to the c-treeACE Database Engine.
Define() - Defines and creates a "customer master" (custmast) table/file.
Manage() - Adds a few rows/records; Reads the rows/records back from the database;
displays the column/field content; and then deletes the rows/records.
Done() - Disconnects from c-treeACE Database Engine.
Note our simple PHP script:
<?php
print("<html>\n");
print("<head>\n");
print("\t<title>PHP Tutorial 1</title>\n");
print("</head>\n");
print("<body>\n");
//
// Implementation of the concept of "init, define, manage and you're done..."
//
$session = Initialize();
Defines($session);
Manage($session);
Done($session);
We suggest opening the source code with your own editor.
Continue now to review these four steps.
Introductory Tutorial
All Rights Reserved 38 www.faircom.com
4.1 Init
First we need to open a connection to a database by providing the c-treeACE Database Engine
with a user name, password and the database name.
Below is the code for Initialize():
//
// Initialize()
//
// Perform the minimum requirement of logging onto the c-tree Server
//
function Initialize() {
print("\t<h4>INIT</h4>\n");
// connect to server
print("\t\tLogon to server...<br>\n");
$ses = ctsql_connect("localhost:ctreeSQL", "admin", "ADMIN");
if (!$ses)
Handle_Error("ctsql_connect()");
return ($ses);
}
Introductory Tutorial
All Rights Reserved 39 www.faircom.com
4.2 Define
The define step is where specific data definitions are established by your application and/or
process. This involves defining columns/fields and creating the tables/files with optional indices.
Below is the code for Define():
//
// Define()
//
// Create the table for containing a list of existing customers
//
function Defines($ses) {
print("\t<h4>DEFINE</h4>\n");
// create table
print("\t\tCreate table...<br>\n");
$qry = ctsql_query(
"CREATE TABLE custmast (
cm_custnumb CHAR(4),
cm_custzipc CHAR(9),
cm_custstat CHAR(2),
cm_custrtng CHAR(1),
cm_custname VARCHAR(47),
cm_custaddr VARCHAR(47),
cm_custcity VARCHAR(47))",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE TABLE)");
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
Introductory Tutorial
All Rights Reserved 40 www.faircom.com
4.3 Manage
The manage step provides data management functionality for your application and/or process.
Below is the code for Manage():
//
// Manage()
//
// This function performs simple record functions of add, delete and gets
//
function Manage($ses) {
print("\t<h4>MANAGE</h4>\n");
// delete any existing records
Delete_Records($ses);
// populate the table with data
Add_Records($ses);
// display contents of table
Display_Records($ses);
}
//
// Delete_Records()
//
// This function deletes all the records in the table
//
function Delete_Records ($ses) {
print("\t\tDelete records...<br>\n");
$qry = ctsql_query("DELETE FROM custmast", $ses);
if (!$qry)
if (100 == ctsql_errno())
return;
else
Handle_Error("ctsql_query(DELETE)");
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
//
// Add_Records()
//
// This function adds records to a table in the database from an
// array of strings
//
function Add_Records ($ses) {
Introductory Tutorial
All Rights Reserved 41 www.faircom.com
print("\t\tAdd records...<br>\n");
$data = array(
"('1000','92867','CA','1','Bryan Williams','2999 Regency','Orange')",
"('1001','61434','CT','1','Michael Jordan','13 Main','Harford')",
"('1002','73677','GA','1','Joshua Brown','4356 Cambridge','Atlanta')",
"('1003','10034','MO','1','Keyon Dooling','19771 Park Avenue','Columbia')"
);
foreach ($data as $values) {
$qry = ctsql_query("INSERT INTO custmast VALUES $values", $ses);
if (!$qry)
Handle_Error("ctsql_query(INSERT)");
}
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
//
// Display_Records()
//
// This function displays the contents of a table.
//
function Display_Records ($ses) {
print("\t\tDisplay records...<br>\n");
$qry = ctsql_query("SELECT cm_custnumb \"Number\", cm_custname \"Name\" FROM custmast",
$ses);
if (!is_resource($qry))
Handle_Error("ctsql_query(SELECT)");
else {
print("\t\t<TABLE border=1>\n\t\t\t<TR><TH>Number</TH><TH>Name</TH></TR>\n");
while ($values = ctsql_fetch_row($qry)) {
print("\t\t\t<TR>");
foreach ($values as $content) {
if (is_null($content))
print ("<TD>NULL</TD>");
else
print ("<TD>$content</TD>");
}
print("</TR>\n");
}
print("\t\t</TABLE>\n");
if (ctsql_errno())
Handle_Error("ctsql_fetch_row()");
ctsql_free_result($qry);
}
}
Introductory Tutorial
All Rights Reserved 42 www.faircom.com
4.4 Done
When an application and/or process has completed operations with the database, it must release
resources by disconnecting from the database engine.
Below is the code for Done():
//
// Done()
//
// This function handles the housekeeping of closing, freeing,
// disconnecting and logging out of the database
//
function Done ($ses) {
print("\t<h4>DONE</h4>\n");
// logout
print("\t\tLogout...<br>\n");
ctsql_close($ses);
}
Introductory Tutorial
All Rights Reserved 43 www.faircom.com
4.5 Additional Resources
We encourage you to explore the additional resources listed here:
Complete source code for this tutorial can be found in PHP_Tutorial1.php in your installation
directory, within the sql.php\tutorials directory for your platform. Example for the Windows
platform:
C:\FairCom\V*\win32\sdk\sql.php\tutorials\PHP_Tutorial1.php
(If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and
replace sdk with Driver.)
Additional documentation may be found on the FairCom Web site at: www.faircom.com
Relationships
All Rights Reserved 44 www.faircom.com
5. Relationships
..\sdk\sql.php\tutorials\PHP_Tutorial2.php
If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and replace
sdk with Driver.
Note: The code shown in this section if found in the version of the tutorial that uses the c-treeACE sql.php API. If you are using the c-treeACE SQL ODBC API to interface with PHP, the general flow of the tutorial will be the same, but the specifics will differ in some places due to the differences between sql.php and ODBC. Consult the source code for the specific version of the tutorial you are using for the exact coding techniques.
Now we will build some table/file relationships using the c-treeACE SQL PHP Interface.
This tutorial will advance the concepts introduced in the first tutorial by expanding the number of
tables. We will define key columns/fields and create specific indices for each table to form a
relational model database.
Like all other examples in the c-tree tutorial series, this tutorial simplifies the creation and use of a
database into four simple steps: Initialize(), Define(), Manage(), and You’re Done() !
Tutorial #2: Relational Model and Indexing
Here we add a bit more complexity, introducing multiple tables, with related indices in order to
form a simple "relational" database simulating an Order Entry system. Here is an overview of
what will be created:
Initialize() - Connects to the c-treeACE Database Engine.
Define() - Defines and creates the "custmast", "custordr", "ordritem" and the
"itemmast" tables/files with related indices.
Manage() - Adds some related rows/records to all tables/files. Then queries the
database.
Relationships
All Rights Reserved 45 www.faircom.com
Done() - Disconnects from c-treeACE Database Engine.
Note our simple PHP script:
<?php
print("<html>\n");
print("<head>\n");
print("\t<title>PHP Tutorial 2</title>\n");
print("</head>\n");
print("<body>\n");
//
// Implementation of the concept of "init, define, manage and you're done..."
//
$session = Initialize();
Defines($session);
Manage($session);
Done($session);
We suggest opening the source code with your own editor.
Continue now to review these four steps.
Relationships
All Rights Reserved 46 www.faircom.com
5.1 Init
First we need to open a connection to a database by providing the c-treeACE Database Engine
with a user name, password and the database name.
Below is the code for Initialize():
//
// Initialize()
//
// Perform the minimum requirement of logging onto the c-tree Server
//
function Initialize() {
print("\t<h4>INIT</h4>\n");
// connect to server
print("\t\tLogon to server...<br>\n");
$ses = ctsql_connect("localhost:ctreeSQL", "admin", "ADMIN");
if (!$ses)
Handle_Error("ctsql_connect()");
return ($ses);
}
Relationships
All Rights Reserved 47 www.faircom.com
5.2 Define
The define step is where specific data definitions are established by your application and/or
process. This involves defining columns/fields and creating the tables/files with optional indices.
Below is the code for Define():
//
// Define()
//
// Create the tables
//
function Defines($ses) {
print("\t<h4>DEFINE</h4>\n");
Create_CustomerMaster_Table($ses);
Create_CustomerOrders_Table($ses);
Create_OrderItems_Table($ses);
Create_ItemMaster_Table($ses);
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
//
// Create_CustomerMaster_Table()
//
// Create the table CustomerMaster
//
function Create_CustomerMaster_Table ($ses) {
print("\t\ttable CustomerMaster<br>\n");
$qry = ctsql_query(
"CREATE TABLE custmast (
cm_custnumb CHAR(4),
cm_custzipc CHAR(9),
cm_custstat CHAR(2),
cm_custrtng CHAR(1),
cm_custname VARCHAR(47),
cm_custaddr VARCHAR(47),
cm_custcity VARCHAR(47))",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE TABLE)");
$qry = ctsql_query(
"CREATE UNIQUE INDEX cm_custnumb_idx ON custmast (cm_custnumb)",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE INDEX)");
}
Relationships
All Rights Reserved 48 www.faircom.com
//
// Create_CustomerOrders_Table()
//
// Create the table CustomerOrders
//
function Create_CustomerOrders_Table ($ses) {
print("\t\ttable CustomerOrders<br>\n");
$qry = ctsql_query(
"CREATE TABLE custordr (
co_ordrdate DATE,
co_promdate DATE,
co_ordrnumb CHAR(6),
co_custnumb CHAR(4))",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE TABLE)");
$qry = ctsql_query(
"CREATE UNIQUE INDEX co_ordrnumb_idx ON custordr (co_ordrnumb)",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE INDEX)");
$qry = ctsql_query(
"CREATE INDEX co_custnumb_idx ON custordr (co_custnumb)",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE INDEX)");
}
//
// Create_OrderItems_Table()
//
// Create the table OrderItems
//
function Create_OrderItems_Table ($ses) {
print("\t\ttable OrderItems<br>\n");
$qry = ctsql_query(
"CREATE TABLE ordritem (
oi_sequnumb SMALLINT,
oi_quantity SMALLINT,
oi_ordrnumb CHAR(6),
oi_itemnumb CHAR(5))",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE TABLE)");
$qry = ctsql_query(
"CREATE UNIQUE INDEX oi_ordrnumb_idx ON ordritem (oi_ordrnumb, oi_sequnumb)",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE INDEX)");
$qry = ctsql_query(
"CREATE INDEX oi_itemnumb_idx ON ordritem (oi_itemnumb)",
$ses);
if (!$qry)
Relationships
All Rights Reserved 49 www.faircom.com
Handle_Error("ctsql_query(CREATE INDEX)");
}
//
// Create_ItemMaster_Table()
//
// Create the table ItemMaster
//
function Create_ItemMaster_Table ($ses) {
print("\t\ttable ItemMaster<br>\n");
$qry = ctsql_query(
"CREATE TABLE itemmast (
im_itemwght INTEGER,
im_itempric MONEY,
im_itemnumb CHAR(5),
im_itemdesc VARCHAR(47))",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE TABLE)");
$qry = ctsql_query(
"CREATE UNIQUE INDEX im_itemnumb_idx ON itemmast (im_itemnumb)",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE INDEX)");
}
Relationships
All Rights Reserved 50 www.faircom.com
5.3 Manage
The manage step provides data management functionality for your application and/or process.
Below is the code for Manage():
//
// Manage()
//
// Populates table and performs a simple query
//
function Manage($ses) {
print("\t<h4>MANAGE</h4>\n");
// populate the tables with data
Add_CustomerMaster_Records($ses);
Add_CustomerOrders_Records($ses);
Add_OrderItems_Records($ses);
Add_ItemMaster_Records($ses);
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
// perform a query:
// list customer name and total amount per order
// name total
// @@@@@@@@@@@@@ $xx.xx
// for each order in the CustomerOrders table
// fetch order number
// fetch customer number
// fetch name from CustomerMaster table based on customer number
// for each order item in OrderItems table
// fetch item quantity
// fetch item number
// fetch item price from ItemMaster table based on item number
// next
// next
$qry = ctsql_query(
"SELECT cm_custname \"Name\", SUM(im_itempric * oi_quantity) \"Total\"" .
"FROM custmast, custordr, ordritem, itemmast " .
"WHERE co_custnumb = cm_custnumb AND co_ordrnumb = oi_ordrnumb AND oi_itemnumb =
im_itemnumb " .
"GROUP BY cm_custnumb, cm_custname",
$ses);
if (!is_resource($qry))
Handle_Error("ctsql_query(SELECT)");
else {
print("\t\t<TABLE border=1>\n\t\t\t<TR><TH>Name</TH><TH>Total</TH></TR>\n");
while ($values = ctsql_fetch_row($qry)) {
Relationships
All Rights Reserved 51 www.faircom.com
print("\t\t\t<TR>");
foreach ($values as $content) {
if (is_null($content))
print ("<TD>NULL</TD>");
else
print ("<TD>$content</TD>");
}
print("</TR>\n");
}
print("\t\t</TABLE>\n");
if (ctsql_errno())
Handle_Error("ctsql_fetch_row()");
ctsql_free_result($qry);
}
}
//
// Add_CustomerMaster_Records()
//
// This function adds records to table CustomerMaster from an
// array of strings
//
function Add_CustomerMaster_Records ($ses) {
print("\t\tAdd records in table CustomerMaster...<br>\n");
$data = array(
"('1000','92867','CA','1','Bryan Williams','2999 Regency','Orange')",
"('1001','61434','CT','1','Michael Jordan','13 Main','Harford')",
"('1002','73677','GA','1','Joshua Brown','4356 Cambridge','Atlanta')",
"('1003','10034','MO','1','Keyon Dooling','19771 Park Avenue','Columbia')"
);
Delete_Records($ses, "custmast");
foreach ($data as $values) {
$qry = ctsql_query("INSERT INTO custmast VALUES $values", $ses);
if (!$qry)
Handle_Error("ctsql_query(INSERT)");
}
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
//
// Add_CustomerOrders_Records()
//
// This function adds records to table CustomerOrders from an
// array of strings
//
function Add_CustomerOrders_Records ($ses) {
print("\t\tAdd records in table CustomerOrders...<br>\n");
$data = array(
"('09/01/2002','09/05/2002','1','1001')",
"('09/02/2002','09/06/2002','2','1002')"
);
Relationships
All Rights Reserved 52 www.faircom.com
Delete_Records($ses, "custordr");
foreach ($data as $values) {
$qry = ctsql_query("INSERT INTO custordr VALUES $values", $ses);
if (!$qry)
Handle_Error("ctsql_query(INSERT)");
}
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
//
// Add_OrderItems_Records()
//
// This function adds records to table OrderItems from an
// array of strings
//
function Add_OrderItems_Records ($ses) {
print("\t\tAdd records in table OrderItems...<br>\n");
$data = array(
"(1,2,'1','1')",
"(2,1,'1','2')",
"(3,1,'1','3')",
"(1,3,'2','3')"
);
Delete_Records($ses, "ordritem");
foreach ($data as $values) {
$qry = ctsql_query("INSERT INTO ordritem VALUES $values", $ses);
if (!$qry)
Handle_Error("ctsql_query(INSERT)");
}
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
//
// Add_ItemMaster_Records()
//
// This function adds records to table ItemMaster from an
// array of strings
//
function Add_ItemMaster_Records ($ses) {
print("\t\tAdd records in table ItemMaster...<br>\n");
$data = array(
"(10,19.95,'1','Hammer')",
"(3, 9.99,'2','Wrench')",
"(4, 16.59,'3','Saw')",
"(1, 3.98,'4','Pliers')"
);
Delete_Records($ses, "itemmast");
Relationships
All Rights Reserved 53 www.faircom.com
foreach ($data as $values) {
$qry = ctsql_query("INSERT INTO itemmast VALUES $values", $ses);
if (!$qry)
Handle_Error("ctsql_query(INSERT)");
}
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
//
// Delete_Records()
//
// This function deletes all the records in a tables
//
function Delete_Records ($ses, $table) {
print("\t\tDelete records...<br>\n");
$qry = ctsql_query("DELETE FROM $table", $ses);
if (!$qry)
if (100 == ctsql_errno())
return;
else
Handle_Error("ctsql_query(DELETE)");
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
Relationships
All Rights Reserved 54 www.faircom.com
5.4 Done
When an application and/or process has completed operations with the database, it must release
resources by disconnecting from the database engine.
Below is the code for Done():
//
// Done()
//
// This function handles the housekeeping of closing, freeing,
// disconnecting and logging out of the database
//
function Done ($ses) {
print("\t<h4>DONE</h4>\n");
// logout
print("\t\tLogout...<br>\n");
ctsql_close($ses);
}
Relationships
All Rights Reserved 55 www.faircom.com
5.5 Additional Resources
We encourage you to explore the additional resources listed here:
Complete source code for this tutorial can be found in PHP_Tutorial2.php in your installation
directory, within the sql.php\tutorials directory for your platform. Example for the Windows
platform:
C:\FairCom\V*\win32\sdk\sql.php\tutorials\PHP_Tutorial2.php
(If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and
replace sdk with Driver.)
Additional documentation may be found on the FairCom Web site at: www.faircom.com
Record/Row Locking
All Rights Reserved 56 www.faircom.com
6. Record/Row Locking
..\sdk\sql.php\tutorials\PHP_Tutorial3.php
If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and replace
sdk with Driver.
Note: The code shown in this section if found in the version of the tutorial that uses the c-treeACE sql.php API. If you are using the c-treeACE SQL ODBC API to interface with PHP, the general flow of the tutorial will be the same, but the specifics will differ in some places due to the differences between sql.php and ODBC. Consult the source code for the specific version of the tutorial you are using for the exact coding techniques.
Now we will explore row/record locks using the c-treeACE SQL PHP Interface.
The functionality for this tutorial focuses on inserting/adding rows/records, then updating a single
row/record in the customer master table under locking control. The application will pause after a
LOCK is placed on a row/record. Another instance of this application should then be launched,
which will block, waiting on the lock held by the first instance. Pressing the <Enter> key will
enable the first instance to proceed. This will result in removing the lock thereby allowing the
second instance to continue execution. Launching two processes provides a visual demonstration
of the effects of locking and a basis for experimentation on your own.
Like all other examples in the c-tree tutorial series, this tutorial simplifies the creation and use of a
database into four simple steps: Initialize(), Define(), Manage(), and you’re Done() !
Tutorial #3: Locking
Here we demonstrate the enforcement of data integrity by introducing record/row "locking".
Initialize() - Connects to the c-treeACE Database Engine.
Define() - Defines and creates a "customer master" (custmast) table/file.
Manage() - Adds a few rows/records; Reads the rows/records back from the database;
displays the column/field content. Then demonstrates an update operation under locking
control, and a scenario that shows a locking conflict.
Done() - Disconnects from c-treeACE Database Engine.
Note our simple PHP script:
<?php
print("<html>\n");
print("<head>\n");
print("\t<title>PHP Tutorial 3</title>\n");
print("</head>\n");
print("<body>\n");
//
// Implementation of the concept of "init, define, manage and you're done..."
//
$session = Initialize();
Record/Row Locking
All Rights Reserved 57 www.faircom.com
Defines($session);
Manage($session);
Done($session);
We suggest opening the source code with your own editor.
Continue now to review these four steps.
Record/Row Locking
All Rights Reserved 58 www.faircom.com
6.1 Init
First we need to open a connection to a database by providing the c-treeACE Database Engine
with a user name, password and the database name.
Below is the code for Initialize():
//
// Initialize()
//
// Perform the minimum requirement of logging onto the c-tree Server
//
function Initialize() {
echo "<h4>INIT</h4>\n";
// connect to server
$ses = ctsql_connect("localhost:ctreeSQL", "admin", "ADMIN");
if (!$ses)
Handle_Error("ctsql_connect()");
return ($ses);
}
Record/Row Locking
All Rights Reserved 59 www.faircom.com
6.2 Define
The define step is where specific data definitions are established by your application and/or
process. This involves defining columns/fields and creating the tables/files with optional indices.
Below is the code for Define():
//
// Define()
//
// Create the table for containing a list of existing customers
//
function Defines($ses) {
echo "<h4>DEFINE</h4>\n";
$qry = ctsql_query(
"CREATE TABLE custmast (
cm_custnumb CHAR(4),
cm_custzipc CHAR(9),
cm_custstat CHAR(2),
cm_custrtng CHAR(1),
cm_custname VARCHAR(47),
cm_custaddr VARCHAR(47),
cm_custcity VARCHAR(47))",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE TABLE)");
$qry = ctsql_query(
"CREATE UNIQUE INDEX cm_custnumb_idx ON custmast (cm_custnumb)",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE INDEX)");
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
Record/Row Locking
All Rights Reserved 60 www.faircom.com
6.3 Manage
The manage step provides data management functionality for your application and/or process.
Below is the code for Manage():
//
// Manage()
//
// This function performs simple record functions of add, delete and gets
//
function Manage($ses) {
echo "<h4>MANAGE</h4>\n";
// delete any existing records
Delete_Records($ses);
// populate the table with data
Add_CustomerMaster_Records($ses);
// display contents of table
Display_Records($ses);
// update a record under locking control
Update_CustomerMaster_Record($ses);
// display again after update and effects of lock
Display_Records($ses);
}
//
// Delete_Records()
//
// This function deletes all the records in the table
//
function Delete_Records ($ses) {
echo "Delete records...<br>\n";
$qry = ctsql_query("DELETE FROM custmast", $ses);
if (!$qry)
if (100 == ctsql_errno())
return;
else
Handle_Error("ctsql_query(DELETE)");
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
//
// Add_CustomerMaster_Records()
Record/Row Locking
All Rights Reserved 61 www.faircom.com
//
// This function adds records to table CustomerMaster from an
// array of strings
//
function Add_CustomerMaster_Records ($ses) {
echo "Add records...<br>\n";
$data = array(
"('1000','92867','CA','1','Bryan Williams','2999 Regency','Orange')",
"('1001','61434','CT','1','Michael Jordan','13 Main','Harford')",
"('1002','73677','GA','1','Joshua Brown','4356 Cambridge','Atlanta')",
"('1003','10034','MO','1','Keyon Dooling','19771 Park Avenue','Columbia')"
);
foreach ($data as $values) {
$qry = ctsql_query("INSERT INTO custmast VALUES $values", $ses);
if (!$qry)
Handle_Error("ctsql_query(INSERT)");
}
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
//
// Display_Records()
//
// This function displays the contents of a table.
//
function Display_Records ($ses) {
echo "Display records...<br>\n";
$qry = ctsql_query("SELECT cm_custnumb \"Number\", cm_custname \"Name\" FROM custmast",
$ses);
if (!is_resource($qry))
Handle_Error("ctsql_query(SELECT)");
else {
print("<TABLE border=1><TR><TH>Number</TH><TH>Name</TH></TR>\n");
while ($values = ctsql_fetch_row($qry)) {
print("<TR>");
foreach ($values as $content) {
if (is_null($content))
print ("<TD>NULL</TD>");
else
print ("<TD>$content</TD>");
}
print("</TR>\n");
}
print("</TABLE>\n");
if (ctsql_errno())
Handle_Error("ctsql_fetch_row()");
ctsql_free_result($qry);
}
}
Record/Row Locking
All Rights Reserved 62 www.faircom.com
//
// Update_CustomerMaster_Records()
//
// Update one record under locking control to demonstrate the effects
// of locking
//
function Update_CustomerMaster_Records ($ses) {
echo "Display records...<br>\n";
}
Record/Row Locking
All Rights Reserved 63 www.faircom.com
6.4 Done
When an application and/or process has completed operations with the database, it must release
resources by disconnecting from the database engine.
Below is the code for Done():
//
// Done()
//
// This function handles the housekeeping of closing, freeing,
// disconnecting and logging out of the database
//
function Done ($ses) {
echo "<h4>DONE</h4>\n";
// logout
ctsql_close($ses);
}
Record/Row Locking
All Rights Reserved 64 www.faircom.com
6.5 Additional Resources
We encourage you to explore the additional resources listed here:
Complete source code for this tutorial can be found in PHP_Tutorial3.php in your installation
directory, within the sql.php\tutorials directory for your platform. Example for the Windows
platform:
C:\FairCom\V*\win32\sdk\sql.php\tutorials\PHP_Tutorial3.php
(If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and
replace sdk with Driver.)
Additional documentation may be found on the FairCom Web site at: www.faircom.com
Transaction Processing
All Rights Reserved 65 www.faircom.com
7. Transaction Processing
..\sdk\sql.php\tutorials\PHP_Tutorial4.php
If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and replace
sdk with Driver.
Note: The code shown in this section if found in the version of the tutorial that uses the c-treeACE sql.php API. If you are using the c-treeACE SQL ODBC API to interface with PHP, the general flow of the tutorial will be the same, but the specifics will differ in some places due to the differences between sql.php and ODBC. Consult the source code for the specific version of the tutorial you are using for the exact coding techniques.
Now we will discuss transaction processing as it relates to the c-treeACE SQL PHP Interface.
Transaction processing provides a safe method by which multiple database operations spread
across separate tables/files are guaranteed to be atomic. By atomic, we mean that, within a
transaction, either all of the operations succeed or none of the operations succeed. This "either
all or none" atomicity insures that the integrity of the data in related tables/files is secure.
Like all other examples in the c-tree tutorial series, this tutorial simplifies the creation and use of a
database into four simple steps: Initialize(), Define(), Manage(), and You’re Done() !
Tutorial #4: Transaction Processing
Here we demonstrate transaction control.
Initialize() - Connects to the c-treeACE Database Engine.
Define() - Defines and creates our four tables/files.
Manage() - Adds rows/records to multiple tables/files under transaction control.
Done() - Disconnects from c-treeACE Database Engine.
Note our simple PHP script:
<?php
print("<html>\n");
print("<head>\n");
print("\t<title>PHP Tutorial 4</title>\n");
print("</head>\n");
print("<body>\n");
//
// Implementation of the concept of "init, define, manage and you're done..."
//
$session = Initialize();
Defines($session);
Manage($session);
Done($session);
We suggest opening the source code with your own editor.
Continue now to review these four steps.
Transaction Processing
All Rights Reserved 66 www.faircom.com
Transaction Processing
All Rights Reserved 67 www.faircom.com
7.1 Init
First we need to open a connection to a database by providing the c-treeACE Database Engine
with a user name, password and the database name.
Below is the code for Initialize():
//
// Initialize()
//
// Perform the minimum requirement of logging onto the c-tree Server
//
function Initialize() {
print("\t<h4>INIT</h4>\n");
// connect to server
print("\t\tLogon to server...<br>\n");
$ses = ctsql_connect("localhost:ctreeSQL", "admin", "ADMIN");
if (!$ses)
Handle_Error("ctsql_connect()");
return ($ses);
}
Transaction Processing
All Rights Reserved 68 www.faircom.com
7.2 Define
The define step is where specific data definitions are established by your application and/or
process. This involves defining columns/fields and creating the tables/files with optional indices.
Below is the code for Define():
//
// Define()
//
// Create the tables
//
function Defines($ses) {
print("\t<h4>DEFINE</h4>\n");
// delete tables ...
Delete_Tables($ses);
// ...and re-create them with constraints
Create_CustomerMaster_Table($ses);
Create_CustomerOrders_Table($ses);
Create_OrderItems_Table($ses);
Create_ItemMaster_Table($ses);
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
//
// Create_CustomerMaster_Table()
//
// Create the table CustomerMaster
//
function Create_CustomerMaster_Table ($ses) {
print("\t\ttable CustomerMaster<br>\n");
$qry = ctsql_query(
"CREATE TABLE custmast (
cm_custnumb CHAR(4) PRIMARY KEY,
cm_custzipc CHAR(9),
cm_custstat CHAR(2),
cm_custrtng CHAR(1),
cm_custname VARCHAR(47),
cm_custaddr VARCHAR(47),
cm_custcity VARCHAR(47))",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE TABLE)");
}
//
// Create_CustomerOrders_Table()
//
Transaction Processing
All Rights Reserved 69 www.faircom.com
// Create the table CustomerOrders
//
function Create_CustomerOrders_Table ($ses) {
print("\t\ttable CustomerOrders<br>\n");
$qry = ctsql_query(
"CREATE TABLE custordr (
co_ordrdate DATE,
co_promdate DATE,
co_ordrnumb CHAR(6) PRIMARY KEY,
co_custnumb CHAR(4),
FOREIGN KEY (co_custnumb) REFERENCES custmast)",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE TABLE)");
}
//
// Create_OrderItems_Table()
//
// Create the table OrderItems
//
function Create_OrderItems_Table ($ses) {
print("\t\ttable OrderItems<br>\n");
$qry = ctsql_query(
"CREATE TABLE ordritem (
oi_sequnumb SMALLINT,
oi_quantity SMALLINT,
oi_ordrnumb CHAR(6),
oi_itemnumb CHAR(5),
FOREIGN KEY (oi_itemnumb) REFERENCES itemmast,
FOREIGN KEY (oi_ordrnumb) REFERENCES custordr)",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE TABLE)");
}
//
// Create_ItemMaster_Table()
//
// Create the table ItemMaster
//
function Create_ItemMaster_Table ($ses) {
print("\t\ttable ItemMaster<br>\n");
$qry = ctsql_query(
"CREATE TABLE itemmast (
im_itemwght INTEGER,
im_itempric MONEY,
im_itemnumb CHAR(5) PRIMARY KEY,
im_itemdesc VARCHAR(47))",
$ses);
if (!$qry)
Handle_Error("ctsql_query(CREATE TABLE)");
}
Transaction Processing
All Rights Reserved 70 www.faircom.com
7.3 Manage
The manage step provides data management functionality for your application and/or process.
Below is the code for Manage():
//
// Manage()
//
// Populates table and perform a simple query
//
function Manage($ses) {
print("\t<h4>MANAGE</h4>\n");
// populate the tables with data
Add_CustomerMaster_Records($ses);
Add_ItemMaster_Records($ses);
Add_Transactions($ses);
// display the orders and their items
Display_CustomerOrders($ses);
Display_OrderItems($ses);
}
//
// Delete_Tables()
//
// This function removes all existing tables
//
function Delete_Tables ($ses) {
$qry = ctsql_query("DROP TABLE ordritem", $ses);
if (!$qry)
Handle_Error("ctsql_query(DROP TABLE)");
$qry = ctsql_query("DROP TABLE custordr", $ses);
if (!$qry)
Handle_Error("ctsql_query(DROP TABLE)");
$qry = ctsql_query("DROP TABLE custmast", $ses);
if (!$qry)
Handle_Error("ctsql_query(DROP TABLE)");
$qry = ctsql_query("DROP TABLE itemmast", $ses);
if (!$qry)
Handle_Error("ctsql_query(DROP TABLE)");
}
//
// Add_CustomerMaster_Records()
//
// This function adds records to table CustomerMaster from an
Transaction Processing
All Rights Reserved 71 www.faircom.com
// array of strings
//
function Add_CustomerMaster_Records ($ses) {
print("\t\tAdd records in table CustomerMaster...<br>\n");
$data = array(
"('1000','92867','CA','1','Bryan Williams','2999 Regency','Orange')",
"('1001','61434','CT','1','Michael Jordan','13 Main','Harford')",
"('1002','73677','GA','1','Joshua Brown','4356 Cambridge','Atlanta')",
"('1003','10034','MO','1','Keyon Dooling','19771 Park Avenue','Columbia')"
);
foreach ($data as $values) {
$qry = ctsql_query("INSERT INTO custmast VALUES $values", $ses);
if (!$qry)
Handle_Error("ctsql_query(INSERT)");
}
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
//
// Add_ItemMaster_Records()
//
// This function adds records to table ItemMaster from an
// array of strings
//
function Add_ItemMaster_Records ($ses) {
print("\t\tAdd records in table ItemMaster...<br>\n");
$data = array(
"(10,19.95,'1','Hammer')",
"(3, 9.99,'2','Wrench')",
"(4, 16.59,'3','Saw')",
"(1, 3.98,'4','Pliers')"
);
foreach ($data as $values) {
$qry = ctsql_query("INSERT INTO itemmast VALUES $values", $ses);
if (!$qry)
Handle_Error("ctsql_query(INSERT)");
}
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
//
// Add_Transactions()
//
// Add an Order and associated Items "as a transaction" to their
// respective tables. A transaction is committed or aborted if the
// customer number on the order is confirmed valid. Likewise each
// item in the order is verified to be a valid item.
//
function Add_Transactions ($ses) {
print("\t\tAdd transaction records...<br>\n");
Transaction Processing
All Rights Reserved 72 www.faircom.com
$orders = array(
array(
'ordrdate' => '09/01/2002',
'promdate' => '09/05/2002',
'ordrnumb' => '1',
'custnumb' => '1001'
),
array(
'ordrdate' => '09/02/2002',
'promdate' => '09/06/2002',
'ordrnumb' => '2',
'custnumb' => '9999' // bad customer number
),
array(
'ordrdate' => '09/22/2002',
'promdate' => '09/26/2002',
'ordrnumb' => '3',
'custnumb' => '1003'
)
);
$items = array(
array(
'ordrnumb' => '1',
'sequnumb' => '1',
'quantity' => '2',
'itemnumb' => '1'
),
array(
'ordrnumb' => '1',
'sequnumb' => '2',
'quantity' => '1',
'itemnumb' => '2'
),
array(
'ordrnumb' => '2',
'sequnumb' => '1',
'quantity' => '1',
'itemnumb' => '3'
),
array(
'ordrnumb' => '2',
'sequnumb' => '2',
'quantity' => '3',
'itemnumb' => '4'
),
array(
'ordrnumb' => '3',
'sequnumb' => '1',
'quantity' => '2',
'itemnumb' => '3'
),
array(
'ordrnumb' => '3',
'sequnumb' => '2',
'quantity' => '2',
'itemnumb' => '99' // bad item number
)
);
foreach ($orders as $order) {
Transaction Processing
All Rights Reserved 73 www.faircom.com
// add order record
$qry = ctsql_query("INSERT INTO custordr VALUES (
'$order[ordrdate]',
'$order[promdate]',
'$order[ordrnumb]',
'$order[custnumb]')",
$ses);
if (!$qry)
Handle_Error("ctsql_query(INSERT)");
foreach ($items as $item) {
// process order items
if ($item[ordrnumb] == $order[ordrnumb]) {
$qr2 = ctsql_query("INSERT INTO ordritem VALUES (
$item[sequnumb],
$item[quantity],
'$item[ordrnumb]',
'$item[itemnumb]')",
$ses);
if (!$qr2)
Handle_Error("ctsql_query(INSERT)");
}
}
}
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
//
// Delete_Records()
//
// This function deletes all the records in a tables
//
function Delete_Records ($ses, $table) {
print("\t\tDelete records...<br>\n");
$qry = ctsql_query("DELETE FROM $table", $ses);
if (!$qry)
if (100 == ctsql_errno())
return;
else
Handle_Error("ctsql_query(DELETE)");
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
}
//
// Display_CustomerOrders()
//
// This function displays the contents of CustomerOrders table.
//
function Display_CustomerOrders ($ses) {
print("\t\tCustomerOrders Table...<br>\n");
$qry = ctsql_query("SELECT co_ordrnumb \"Order\", co_custnumb \"Customer\" FROM custordr",
$ses);
if (!is_resource($qry))
Transaction Processing
All Rights Reserved 74 www.faircom.com
Handle_Error("ctsql_query(SELECT)");
else {
print("\t\t<TABLE border=1>\n\t\t\t<TR><TH>Order</TH><TH>Customer</TH></TR>\n");
while ($values = ctsql_fetch_row($qry)) {
print("\t\t\t<TR>");
foreach ($values as $content) {
if (is_null($content))
print ("<TD>NULL</TD>");
else
print ("<TD>$content</TD>");
}
print("</TR>\n");
}
print("\t\t</TABLE>\n");
if (ctsql_errno())
Handle_Error("ctsql_fetch_row()");
ctsql_free_result($qry);
}
}
//
// Display_OrderItems()
//
// This function displays the contents of OrderItems table.
//
function Display_OrderItems ($ses) {
print("\t\tOrderItems Table...<br>\n");
$qry = ctsql_query("SELECT oi_ordrnumb \"Order\", oi_itemnumb \"Item\" FROM ordritem",
$ses);
if (!is_resource($qry))
Handle_Error("ctsql_query(SELECT)");
else {
print("\t\t<TABLE border=1>\n\t\t\t<TR><TH>Order</TH><TH>Item</TH></TR>\n");
while ($values = ctsql_fetch_row($qry)) {
print("\t\t\t<TR>");
foreach ($values as $content) {
if (is_null($content))
print ("<TD>NULL</TD>");
else
print ("<TD>$content</TD>");
}
print("</TR>\n");
}
print("\t\t</TABLE>\n");
if (ctsql_errno())
Handle_Error("ctsql_fetch_row()");
ctsql_free_result($qry);
}
}
Transaction Processing
All Rights Reserved 75 www.faircom.com
7.4 Done
When an application and/or process has completed operations with the database, it must release
resources by disconnecting from the database engine.
Below is the code for Done():
//
// Done()
//
// This function handles the housekeeping of closing, freeing,
// disconnecting and logging out of the database
//
function Done ($ses) {
print("\t<h4>DONE</h4>\n");
Delete_Tables($ses);
if (!ctsql_commit($ses))
Handle_Error("ctsql_commit()");
// logout
print("\t\tLogout...<br>\n");
ctsql_close($ses);
}
Transaction Processing
All Rights Reserved 76 www.faircom.com
7.5 Additional Resources
We encourage you to explore the additional resources listed here:
Complete source code for this tutorial can be found in PHP_Tutorial4.php in your installation
directory, within the sql.php\tutorials directory for your platform. Example for the Windows
platform:
C:\FairCom\V*\win32\sdk\sql.php\tutorials\PHP_Tutorial4.php
(If you are using c-treeRTG, adjust the path to match your version, e.g., V2.2.0.RTG, and
replace sdk with Driver.)
Additional documentation may be found on the FairCom Web site at: www.faircom.com
Additional Functionality
All Rights Reserved 77 www.faircom.com
8. Additional Functionality
The introductory c-treeACE tutorials have offered a glimpse into the ease and flexibility c-treeACE
provides using only a few basic functions. The c-treeACE interfaces include a rich array of
features for nearly any data management need, such as:
String handling
Currency handling
Date and Time handling
Index and Segment handling
...and many, many more.
FairCom c-treeACE provides a variety of APIs. To learn more about these APIs, see c-treeACE
Interfaces https://docs.faircom.com/readme/v11_5/sdk/.
All Rights Reserved 78 www.faircom.com
9. c-treePHP Functions
In this section, we will be listing the c-treePHP functions in alphabetical order. The function
descriptions include some or all of the following sections:
Declaration
Function and parameter declarations.
Description
A detailed description of the function and parameters.
Parameter [in/out] detail.
Returns
Explanation of the common return values.
Example
A simple programming example.
See also
A list of related functions and other information.
9.1 Resource Types
There are two resource types used in the c-treePHP module. The first is the connection identifier
for a c-treeACE SQL connection. The second resource holds the result of a query.
For example, the following code demonstrates how to connect to c-treeACE SQL, execute a
query, print resulting rows and disconnect from a c-treeACE SQL database:
c-treePHP Example
<?php
/* Connecting, selecting database */
$ses = ctsql_connect("ctreeSQL","ADMIN","ADMIN")
or die("Could not successfully connect to c-treeACE SQL: " . ctsql_error());
echo "Successfully connected to c-treeACE SQL!";
/* Performing SQL query */
$query = "SELECT * FROM my_table";
$result = ctsql_query($query) or die("Query failed : " . ctsql_error());
/* Printing results in HTML */
echo "<table>\n";
while ($line = ctsql_fetch_assoc($result)) {
echo "\t<tr>\n";
c-treePHP Functions
All Rights Reserved 79 www.faircom.com
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
/* Free resultset */
ctsql_free_result($result);
/* Closing connection */
ctsql_close($ses);
?>
9.2 c-treePHP Example
<?php
/* Connecting, selecting database */
$ses = ctsql_connect("ctreeSQL","ADMIN","ADMIN")
or die("Could not successfully connect to c-treeACE SQL: " . ctsql_error());
echo "Successfully connected to c-treeACE SQL!";
/* Performing SQL query */
$query = "SELECT * FROM my_table";
$result = ctsql_query($query) or die("Query failed : " . ctsql_error());
/* Printing results in HTML */
echo "<table>\n";
while ($line = ctsql_fetch_assoc($result)) {
echo "\t<tr>\n";
foreach ($line as $col_value) {
echo "\t\t<td>$col_value</td>\n";
}
echo "\t</tr>\n";
}
echo "</table>\n";
/* Free resultset */
ctsql_free_result($result);
/* Closing connection */
ctsql_close($ses);
?>
c-treePHP Functions
All Rights Reserved 80 www.faircom.com
ctsql_affected_rows
Returns the number of affected rows from the previous c-treePHP operation.
Declaration int ctsql_affected_rows ( [resource connectionID])
Description
ctsql_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or
DELETE query. This will also work with the SELECT statement but only after fetching the rows.
Returns
ctsql_affected_rows() returns the number of rows affected by the last INSERT, UPDATE or
DELETE query associated with connectionID.
Example
<?php
/* connect to database */
$link = ctsql_connect('ctreeSQL', 'admin', 'ADMIN');
if (!$link) {
die('Failed to connect to c-treeACE SQL: ' . ctsql_error());
}
/* this should return the correct numbers of deleted records */
ctsql_query('DELETE FROM mytable WHERE age < 50');
printf("Records deleted: %d\n", ctsql_affected_rows());
/* with a where clause that is never true, it should return 0 */
ctsql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", ctsql_affected_rows());
?>
The above example would produce the following output:
Records deleted: 10
Records deleted: 0
c-treePHP Functions
All Rights Reserved 81 www.faircom.com
ctsql_close
Close a c-treePHP connection.
Declaration bool ctsql_close ( [resource connectionID])
Description
ctsql_close() closes the connection to c-treeACE SQL that is associated with the specified
connection identifier.
ctsql_close() is not usually necessary, as non-persistent open links are automatically closed at
the end of the script’s execution. Additional details on freeing resources can be found in the PHP
documentation.
Returns
Returns TRUE on success or FALSE on failure.
Example
<?php
$link = ctsql_connect('ctreeSQL', 'admin', 'ADMIN');
if (!$link) {
die('Failed to connect to c-treeACE SQL: ' . ctsql_error());
}
echo 'Successfully connected to c-treeACE SQL';
ctsql_close($link);
?>
See also
ctsql_connect(), ctsql_pconnect().
c-treePHP Functions
All Rights Reserved 82 www.faircom.com
ctsql_commit
Commit the current c-treePHP transaction.
Declaration bool ctsql_commit ([resource connectionID])
Description
Commits the current transaction for the database connection specified by the connectionID.
Returns
Returns TRUE on success or FALSE on failure.
c-treePHP Functions
All Rights Reserved 83 www.faircom.com
ctsql_connect
Open a connection to c-treeACE SQL
Declaration resource ctsql_connect ( [string dbname [, string username [, string password]]])
Description
ctsql_connect() establishes a connection to c-treeACE SQL.
The dbname parameter is formatted as one of the usual c-treeACE database names shown
below:
port#@hostname:database
port#@hostname
hostname:database
database (e.g. “6597@localhost:ctreeSQL”)
The link to the server will be closed as soon as the execution of the script ends, unless it’s closed
earlier by explicitly calling ctsql_close().
Returns
Returns a c-treePHP connection identifier on success, or FALSE on failure.
Example <?php
$link = ctsql_connect('ctreeSQL', 'admin', 'ADMIN');
if (!$link) {
die('Failed to connect to c-treeACE SQL: ' . ctsql_error());
}
echo 'Successfully connected to c-treeACE SQL';
ctsql_close($link);
?>
See also
ctsql_pconnect(), ctsql_close().
c-treePHP Functions
All Rights Reserved 84 www.faircom.com
ctsql_end_of_fetch
Returns if there are more rows to fetch.
Declaration bool ctsql_end_of_fetch ( resource QueryID )
Description
ctsql_end_of_fetch() indicates if there are more rows to fetch.
Returns
True if this is the last fetch; otherwise false.
Example
<?php
/* connect to database */
$link = ctsql_connect('ctreeSQL', 'admin', 'ADMIN');
if (!$link) {
die('Failed to connect to c-treeACE SQL: ' . ctsql_error());
}
/* this should return the correct numbers of deleted records */
ctsql_query('DELETE FROM mytable WHERE age < 50');
printf("Records deleted: %d\n", ctsql_affected_rows());
/* with a where clause that is never true, it should return 0 */
ctsql_query('DELETE FROM mytable WHERE 0');
printf("Records deleted: %d\n", ctsql_affected_rows());
?>
The above example would produce the following output:
Records deleted: 10
Records deleted: 0
c-treePHP Functions
All Rights Reserved 85 www.faircom.com
ctsql_errno
Returns the numerical value of the error message from previous c-treePHP operation
Declaration int ctsql_errno ()
Returns
Returns the error number from the most recently executed c-treePHP function (not including
ctsql_error() and ctsql_errno()), or 0 (zero) if no error occurred.
Example
<?php
$link = ctsql_connect("ctreeSQL", "admin", "ADMIN");
if (!$link) {
echo ctsql_errno() . ": " . ctsql_error(). "\n";
}
if (!ctsql_query("SELECT * FROM nonexistenttable", $link)) {
echo ctsql_errno() . ": " . ctsql_error() . "\n";
}
?>
The above example would produce the following output if nonexistenttable does not exist:
-20005: Table/View/Synonym not found
See also
ctsql_error()
c-treePHP Functions
All Rights Reserved 86 www.faircom.com
ctsql_error
Returns the text of the error message from previous c-treePHP operation.
Declaration string ctsql_error ()
Returns
Returns the error text from the most recently executed c-treePHP function, not including
ctsql_error() and ctsql_errno(). An empty string is returned if no error occurred.
Example
<?php
$link = ctsql_connect("ctreeSQL", "admin", "ADMIN");
if (!$link) {
echo ctsql_errno() . ": " . ctsql_error(). "\n";
}
if (!ctsql_query("SELECT * FROM nonexistenttable", $link)) {
echo ctsql_errno() . ": " . ctsql_error() . "\n";
}
?>
The above example would produce the following output:
-20005: Table/View/Synonym not found
See also
ctsql_errno()
c-treePHP Functions
All Rights Reserved 87 www.faircom.com
ctsql_fetch_array
Fetches a result row as both an associative array and a numeric array.
Declaration array ctsql_fetch_array ( resource queryID)
Description
ctsql_fetch_array() is an extended version of ctsql_fetch_row(). In addition to storing the data
in the numeric indices of the result array, it also stores the data in associative indices, using the
field names as keys.
If two or more columns of the result have the same field names, the last column will take
precedence. To access the other column(s) of the same name, you must use the numeric index
of the column or make an alias for the column. For aliased columns, you cannot access the
contents with the original column name (by using ‘field’ in the example given below).
This SELECT query demonstrates aliased duplicate field names:
SELECT table1.field AS foo, table2.field AS bar FROM table1, table2
It is important to note that while ctsql_fetch_row() may be slightly faster, ctsql_fetch_array()
provides a significant added benefit for the performance difference.
Note: Field names returned by this function are case-sensitive.
Returns
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
Example
<?php
ctsql_connect("localhost:ctreeSQL") or
die('Failed to connect to c-treeACE SQL: ' . ctsql_error());
$result = ctsql_query("SELECT id, name FROM mytable");
while ($row = ctsql_fetch_array($result)) {
printf ("ID: %s Name: %s", $row[0], $row["name"]);
}
ctsql_free_result($result);
?>
See also
ctsql_fetch_row(), ctsql_fetch_assoc().
c-treePHP Functions
All Rights Reserved 88 www.faircom.com
ctsql_fetch_assoc
Fetches a result row as an associative array.
Declaration array ctsql_fetch_assoc (resource queryID)
Description
ctsql_fetch_assoc() stores the data in associative indices, using the field names as keys.
If two or more columns of the result have the same field names, the last column will take
precedence. To access the other column(s) of the same name, you either need to access the
result with numeric indices by using ctsql_fetch_row() or add alias names. For aliased columns,
you cannot access the contents with the original column name (by using ‘field’ in this example).
This SELECT statement demonstrates a query with aliased duplicate field names
SELECT table1.field AS foo, table2.field AS bar FROM table1, table2
Note: Field names returned by this function are case-sensitive.
Returns
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
Example
<?php
ctsql_connect("localhost:ctreeSQL") or
die("Failed to connect to c-treeACE SQL: " . ctsql_error());
$result = ctsql_query("SELECT id, name FROM mytable");
while ($row = ctsql_fetch_assoc($result)) {
printf ("ID: %s Name: %s", $row["id"],$row["name"]);
}
ctsql_free_result($result);
?>
See also
ctsql_fetch_row(), ctsql_fetch_array().
c-treePHP Functions
All Rights Reserved 89 www.faircom.com
ctsql_fetch_object
Fetches a result row as an object.
Declaration object ctsql_fetch_object ( resource queryID)
Description
ctsql_fetch_object() is similar to ctsql_fetch_array(), with one difference; an object is returned
instead of an array. Indirectly, this means you may only access the data by the field names, and
not with the offsets (a number is an illegal property name).
Note: Field names returned by this function are case-sensitive.
Comparing performance, this function is identical to ctsql_fetch_array(), and is approximately as
fast as ctsql_fetch_row().
Returns
Returns an object with properties that correspond to the fetched row, or FALSE if there are no
more rows.
Example
<?php
ctsql_connect("localhost:ctreeSQL");
$result = ctsql_query("select * from mytable");
while ($row = ctsql_fetch_object($result)) {
echo $row->user_id;
echo $row->fullname;
}
ctsql_free_result($result);
?>
See also
ctsql_fetch_array(), ctsql_fetch_assoc(), ctsql_fetch_row().
c-treePHP Functions
All Rights Reserved 90 www.faircom.com
ctsql_fetch_row
Returns a result row as an enumerated array.
Declaration array ctsql_fetch_row ( resource queryID)
Description
ctsql_fetch_row() will fetch one row of data from the result associated with the specified query
identifier. The row is returned as an array. Each result column is stored in an array offset, starting
at offset 0.
Subsequent calls to ctsql_fetch_row() return the next row in the result set, or FALSE if there are
no more rows.
Returns
Returns an array that corresponds to the fetched row, or FALSE if there are no more rows.
See also
ctsql_fetch_array(), ctsql_fetch_assoc(), ctsql_fetch_object().
c-treePHP Functions
All Rights Reserved 91 www.faircom.com
ctsql_field_len
Returns the length of the specified field.
Declaration int ctsql_field_len ( resource queryID , int field_offset )
Returns
Returns the length of the specified field.
c-treePHP Functions
All Rights Reserved 92 www.faircom.com
ctsql_field_name
Returns the name of the specified field in a result.
Declaration string ctsql_field_name ( resource queryID , int field_offset )
Description
field_index starts at 0. For example, the index of the third field is 2, the index of the fourth field is
3, etc.
Note: Field names returned by this function are case-sensitive.
Returns
ctsql_field_name() returns the name of the specified field index. queryID must be a valid query
identifier and field_index is the numerical offset of the field.
c-treePHP Functions
All Rights Reserved 93 www.faircom.com
ctsql_field_table
Returns the name of the table containing the specified field.
Declaration string ctsql_field_table ( resource queryID , int field_offset )
Returns
Returns the name of the table containing the specified field.
Example
<?php
ctsql_connect("localhost:ctreeSQL");
$result = ctsql_query("select * from mytable");
printf ("Table containing field ID is:", ctsql_field_table($result, 1));
ctsql_free_result($result);
?>
c-treePHP Functions
All Rights Reserved 94 www.faircom.com
ctsql_field_type
Returns the type of the specified field in a result.
Declaration string ctsql_field_type ( resource queryID , int field_offset )
Description
ctsql_field_type() is similar to ctsql_field_name(). The arguments are identical, but the field
type is returned instead. The field type will be one of “int”, “real”, “string”, and others as detailed in
c-treeACE SQL documentation.
Example
<?php
ctsql_connect("localhost:ctreeSQL");
$result = ctsql_query("select * from mytable");
printf ("Field ID has type: ", ctsql_field_type($result, 1));
ctsql_free_result($result);
?>
c-treePHP Functions
All Rights Reserved 95 www.faircom.com
ctsql_free_result
Frees the result memory for a query.
Declaration bool ctsql_free_result ( resource queryID)
Description
ctsql_free_result() is only necessary if you are concerned about how much memory is used for
queries that return large result sets. All associated result memory is automatically freed at the end
of the script’s execution.
ctsql_free_result() will free all memory associated with the result identifier queryID.
Returns
Returns TRUE on success or FALSE on failure.
c-treePHP Functions
All Rights Reserved 96 www.faircom.com
ctsql_num_fields
Returns the number of fields in result.
Declaration int ctsql_num_fields (resource queryID)
Returns
ctsql_num_fields() returns the number of fields in the result set queryID.
See also
ctsql_query()
c-treePHP Functions
All Rights Reserved 97 www.faircom.com
ctsql_pconnect
Opens a permanent connection to c-treeACE SQL
Declaration resource ctsql_pconnect ( [string dbname [, string username [, string password]]])
Returns
Returns a c-treePHP connection identifier on success, or FALSE on failure.
Note: Currently, this functionality is not available in c-treePHP and this function behaves exactly as ctsql_connect().
c-treePHP Functions
All Rights Reserved 98 www.faircom.com
ctsql_query
Sends a query to c-treeACE SQL.
Declaration resource ctsql_query ( string query [, resource connectionID])
Description
ctsql_query() sends a query to the currently active database on the server that’s associated with
the specified connection identifier. If connectionID isn’t specified, the last used link is assumed.
The query result is buffered. The buffer size is controlled trough the ctsql.rowsperfetch runtime
configuration value. The rows in the buffer are updated when one of the ctsql_fetch..() functions
reaches the end of the buffer.
Note: The query string should not end with a semicolon.
Only for SELECT statements ctsql_query() returns a queryID or FALSE if the query was not
executed correctly. For other type of c-treeACE SQL statements, ctsql_query() returns TRUE on
success and FALSE on error. A non-FALSE return value means that the query was legal and
could be executed by the server. It does not indicate anything about the number of rows affected
or returned. It is perfectly possible for a query to succeed but affect no rows or return no rows.
Assuming the query succeeds, you can call ctsql_affected_rows() to find out how many rows
were affected by a DELETE, INSERT, REPLACE, or UPDATE statement.
Only for SELECT, ctsql_query() returns a new result identifier which you then pass to
ctsql_fetch_array() and other functions dealing with result tables. When you are finished with the
result set, you then free the resources associated with it by calling ctsql_free_result(). This
memory is also automatically freed at the end of the script’s execution.
See also
ctsql_affected_rows(), ctsql_free_result(), ctsql_fetch_array(), ctsql_fetch_row(),
ctsql_fetch_assoc(), ctsql_connect().
c-treePHP Functions
All Rights Reserved 99 www.faircom.com
ctsql_rollback
Rolls back the current open transaction.
Declaration bool ctsql_rollback ( [resource connectionID])
Description
Rolls back the current transaction for the database specified by the connectionID parameter.
Returns
Returns TRUE on success or FALSE on failure.
See also
ctsql_commit()
All Rights Reserved 100 www.faircom.com
10. Index
A Additional Functionality ........................................... 77 Additional Resources ............................43, 55, 64, 76
C Compile the sql.php Extension ......................... 24, 27 Compile the sql.php Extension (Linux/Unix) ..... 31, 33 Configure Microsoft IIS ....................................... 6, 10 Configure PHP ........................................................ 31 Configure the sql.php Extension ............................. 24 Copyright Notice ....................................................... ii c-treePHP Example ................................................ 79 c-treePHP for c-treeACE SQL .................................. 1 c-treePHP Functions............................................... 78 ctsql_affected_rows ................................................ 80 ctsql_close .............................................................. 81 ctsql_commit ........................................................... 82 ctsql_connect .......................................................... 83 ctsql_end_of_fetch.................................................. 84 ctsql_errno .............................................................. 85 ctsql_error ............................................................... 86 ctsql_fetch_array .................................................... 87 ctsql_fetch_assoc ................................................... 88 ctsql_fetch_object ................................................... 89 ctsql_fetch_row ....................................................... 90 ctsql_field_len ......................................................... 91 ctsql_field_name ..................................................... 92 ctsql_field_table ...................................................... 93 ctsql_field_type ....................................................... 94 ctsql_free_result ..................................................... 95 ctsql_num_fields ..................................................... 96 ctsql_pconnect ........................................................ 97 ctsql_query ............................................................. 98 ctsql_rollback .......................................................... 99
D Define ...................................................39, 47, 59, 68 Done .....................................................42, 54, 63, 75
E Error
function, ctsql_errno ........................................... 85 function, ctsql_error ............................................ 86
F FairCom Typographical Conventions ....................... v Functions
ctsql_close .......................................................... 81 ctsql_commit ....................................................... 82 ctsql_connect ...................................................... 83 ctsql_errno .......................................................... 85 ctsql_error ........................................................... 86
ctsql_fetch_array ................................................ 87 ctsql_fetch_assoc .............................................. 88 ctsql_fetch_object .............................................. 89 ctsql_fetch_row .................................................. 90 ctsql_field_len .................................................... 91 ctsql_field_name ................................................ 92 ctsql_field_table ................................................. 93 ctsql_field_type .................................................. 94 ctsql_free_result ................................................. 95 ctsql_num_fields ................................................ 96 ctsql_pconnect ................................................... 97 ctsql_query ......................................................... 98 ctsql_rollback ..................................................... 99 Functions............................................................ 78
I Init ........................................................ 38, 46, 58, 67 Install and Execute the ODBC Tutorials ................ 16 Install Microsoft IIS............................................... 6, 7 Install PHP ............................................... 6, 9, 13, 14 Install the Web Server ..................................... 13, 15 Install unixODBC.................................................... 13 Introductory Tutorial ............................................... 37
M Manage ................................................ 40, 50, 60, 70
P Packages Required for Windows ..............................6
Q Quick Start ................................................................3
R Record/Row Locking .............................................. 56 Relationships ......................................................... 44 Resource types ...................................................... 78 Resource Types ..................................................... 78 Run the ODBC Tutorials with Apache on
Linux/Unix .......................................................... 21 Run the ODBC Tutorials with IIS on Windows ...... 16 Run the sql.php Tutorials with Linux/Unix
Apache ......................................................... 31, 34 Run the sql.php Tutorials with Microsoft IIS .... 24, 29
T Transaction Processing ......................................... 65
U Using PHP on Linux and Unix ............................... 13 Using PHP on Windows ............................................6 Using PHP with the sql.php API ........................ 3, 23 Using the sql.php API on Linux and Unix ........ 23, 31 Using the sql.php API on Windows .................. 23, 24