Sie sind auf Seite 1von 322

myDBR Documentation

myDBR Documentation
Copyright © 2007 - 2018 mydbr.com

About myDBR

myDBR is an enterprise ready reporting system for MySQL and Microsoft SQL Server, Sybase ASE and SQL
Anywhere databases. myDBR scales from personal database reporting tool to enterprise business intelligence
system. Creating and maintaining reports with myDBR is fast, fun and productive.

For more information visit https://mydbr.com


Table of Contents
1. Welcome to myDBR ........................................................................................................................... 1
2. Installation .......................................................................................................................................... 2
Quick Start ..................................................................................................................................... 2
Manual Installation .......................................................................................................................... 2
Prerequisites .................................................................................................................................. 3
PHP ....................................................................................................................................... 3
ionCube PHP loader ............................................................................................................... 3
Database version requirement ................................................................................................ 3
Choosing the Database Driver ................................................................................................ 3
FreeTDS configuration ............................................................................................................ 4
myDBR application ......................................................................................................................... 5
Download the myDBR application ........................................................................................... 5
Select database user for myDBR ............................................................................................ 5
Prepare the report database ................................................................................................... 6
Install the myDBR application ................................................................................................. 8
Installation wizard ................................................................................................................... 9
Optional installations ....................................................................................................................... 9
Image chart support with ChartDirector ................................................................................... 9
wkhtmltopdf - recommended ................................................................................................. 10
Graphviz support .................................................................................................................. 10
Update myDBR ............................................................................................................................ 10
Automatic updater using web interface .................................................................................. 10
Manual update ..................................................................................................................... 11
Scripting the automatic updater ............................................................................................. 11
Scripting the license installation ............................................................................................ 12
Managing large number of installations .................................................................................. 13
Automating license distribution .............................................................................................. 13
Database access .......................................................................................................................... 16
User login ............................................................................................................................ 16
Report execution .................................................................................................................. 18
myDBR License ............................................................................................................................ 18
Requesting a license ............................................................................................................ 18
How many licenses do I need? ............................................................................................. 18
Information contained in the license ...................................................................................... 18
3. Getting started .................................................................................................................................. 20
Creating your first report ............................................................................................................... 20
First report ........................................................................................................................... 20
Assign the report to the myDBR report structure .................................................................... 21
Adding parameters to a report .............................................................................................. 23
Cross-tabulation report .................................................................................................................. 24
Understanding the data parts in a cross-tabulation report ....................................................... 25
Creating your first chart ................................................................................................................ 26
Generating a chart ................................................................................................................ 26
Pageview report ........................................................................................................................... 27
User Parameters .......................................................................................................................... 28
............................................................................................................................................ 28
Basic fields (text/number) ...................................................................................................... 28
Date picker ........................................................................................................................... 30
Default values ...................................................................................................................... 30
Predefined / dynamic parameters .......................................................................................... 31
Select lists ............................................................................................................................ 32
Radio buttons ....................................................................................................................... 33
Checkboxes .......................................................................................................................... 35
Autocomplete fields .............................................................................................................. 36
One-line autocomplete .......................................................................................................... 36

iii
myDBR Documentation

Two-line autocomplete .......................................................................................................... 37


Getting the IDs of the selected autocomplete value ................................................................ 38
Connected parameters ........................................................................................................ 39
Automatic parameters ........................................................................................................... 41
Example: Identifying the user running the report ................................................................... 41
Parameters in linked reports ................................................................................................. 42
Report linking ............................................................................................................................... 43
Linking to column values ...................................................................................................... 43
Linking to parameters ........................................................................................................... 45
Passing on multiple parameters ............................................................................................ 45
Letting the user edit the passed parameters .......................................................................... 46
Specifying the link location .................................................................................................... 46
Output destination of the linked report ................................................................................... 46
Referencing columns and parameters or passing on constants ....................................................... 47
Column reference ................................................................................................................. 47
Parameter reference ............................................................................................................. 48
Passing on constants ........................................................................................................... 48
Referencing crosstab total columns ....................................................................................... 49
Report layout ................................................................................................................................ 49
Placing elements side-by-side using 'dbr.keepwithnext'-command .................................. 50
Using templates .................................................................................................................... 51
Placing elements with the dbr.html-command ........................................................................ 51
Creating editable reports ............................................................................................................... 52
Sample editing functionality ................................................................................................... 52
Creating new database entities (row) .................................................................................... 53
Editing a row, all columns at once ........................................................................................ 54
'Delete a row'-example, use Javascript to enhance editing ...................................................... 56
In-place editing ..................................................................................................................... 57
4. Preferences ...................................................................................................................................... 60
Report categories ......................................................................................................................... 60
Users ........................................................................................................................................... 60
myDBR users ....................................................................................................................... 60
Importing users from another system .................................................................................... 60
Groups ......................................................................................................................................... 61
User group concept .............................................................................................................. 61
Adding group ........................................................................................................................ 61
Removing group ................................................................................................................... 61
Adding a user to a group ...................................................................................................... 61
Remove a user from a group ................................................................................................ 61
Styles ........................................................................................................................................... 61
Row styles ........................................................................................................................... 61
Column styles ....................................................................................................................... 62
Parameter queries ........................................................................................................................ 62
Server side files ........................................................................................................................... 62
............................................................................................................................................ 62
defaults.php .......................................................................................................................... 62
userstyle.css ......................................................................................................................... 63
Templates .................................................................................................................................... 63
Notifications .................................................................................................................................. 63
Login notification .................................................................................................................. 63
Main-screen notification ........................................................................................................ 64
Environmental settings .................................................................................................................. 64
Report Database Setup ........................................................................................................ 64
Authentication ....................................................................................................................... 64
Password settings when using myDBR authentication ............................................................ 65
Single Sign-On (SSO) settings .............................................................................................. 65
Active Directory settings ....................................................................................................... 65
Password reset ..................................................................................................................... 65

iv
myDBR Documentation

Automatic login ..................................................................................................................... 66


Formatting defaults ............................................................................................................... 66
Mail ...................................................................................................................................... 66
OEM .................................................................................................................................... 67
Installed modules .................................................................................................................. 67
Miscellaneous settings .......................................................................................................... 67
Single Sign-On (SSO) ................................................................................................................... 68
Introduction .......................................................................................................................... 68
Authentication protocol .......................................................................................................... 68
Local myDBR login when SSO is enabled ............................................................................. 69
Logout process in SSO ......................................................................................................... 69
Example for integration with SugarCRM ................................................................................ 70
Google authentication ........................................................................................................... 71
Active Directory ............................................................................................................................ 72
Introduction .......................................................................................................................... 72
Active Directory settings ....................................................................................................... 72
Local myDBR login when AD login is enabled ....................................................................... 73
Custom authentication .................................................................................................................. 73
Introduction .......................................................................................................................... 73
Usage .................................................................................................................................. 73
Remote servers ............................................................................................................................ 73
Demo / Localization ...................................................................................................................... 74
Demo ................................................................................................................................... 74
Localization .......................................................................................................................... 74
About ........................................................................................................................................... 74
5. Managing reports ............................................................................................................................. 75
General ........................................................................................................................................ 75
Adding/deleting folders .......................................................................................................... 75
Adding/deleting reports ......................................................................................................... 75
Moving reports and folders ................................................................................................... 76
Defining report parameters .................................................................................................... 76
Report privileges .................................................................................................................. 76
Report access rights ..................................................................................................................... 76
All logged in users ............................................................................................................... 76
Access without login allowed via direct URL .......................................................................... 76
Individual users .................................................................................................................... 76
Groups inside myDBR .......................................................................................................... 76
Identifying the user running the report ................................................................................... 76
Showing report privileges at one glance ................................................................................ 77
Direct URL access to reports ........................................................................................................ 77
URL parameters ................................................................................................................... 77
Generating a direct URL ....................................................................................................... 78
Example ............................................................................................................................... 79
Embedding reports in a web page ......................................................................................... 80
Direct accessible image reports ............................................................................................ 80
Getting only the report object's content .................................................................................. 80
Using HTTP basic access authentication ............................................................................... 80
Statistics ....................................................................................................................................... 81
Localization .................................................................................................................................. 82
Localizing myDBR's User Interface for your own language ..................................................... 82
Multilingual support in myDBR .............................................................................................. 82
Handling dates in string ........................................................................................................ 83
Example of a localized report ................................................................................................ 83
Using DATE.FORMAT .......................................................................................................... 84
Favorites ...................................................................................................................................... 84
Customization ............................................................................................................................... 85
Customize the Main Screen .................................................................................................. 85
Customize the report ............................................................................................................ 86

v
myDBR Documentation

Customize the Top header / dashboard ................................................................................. 86


Customize the PDF output .................................................................................................... 87
Using CSS for customization ................................................................................................ 87
OEM customization ............................................................................................................... 87
Scheduled tasks ........................................................................................................................... 88
Configuration ........................................................................................................................ 88
Synchronization ............................................................................................................................ 89
Options ................................................................................................................................ 90
Utilizing version control ................................................................................................................. 90
Usage .................................................................................................................................. 90
Sample configuration files ..................................................................................................... 91
Additional configuration settings ............................................................................................ 91
6. Commands ....................................................................................................................................... 93
Aggregate functions ...................................................................................................................... 93
Explanation .......................................................................................................................... 94
Example use of an aggregate function .................................................................................. 94
Including header levels in calculation .................................................................................... 95
Calculations .......................................................................................................................... 96
Basic calculation ................................................................................................................... 96
Calculation applied to a crosstable ........................................................................................ 97
Calculation with aggregate column reference ......................................................................... 97
Calculation with horizontal aggregate column reference .......................................................... 98
Combining calculation with horizontal and vertical aggregate column reference ........................ 99
Titles / text ................................................................................................................................... 99
Applying styles ........................................................................................................................... 102
Column hiding .................................................................................................................... 103
Define a column style ......................................................................................................... 103
Summary calculation with column style ................................................................................ 105
Define a row style .............................................................................................................. 105
Define a cell style or class .................................................................................................. 106
Hiding the header from a result table .................................................................................. 107
Header and footer styles ..................................................................................................... 107
Custom CSS class for result tables ..................................................................................... 108
Formatting columns and footers based on data .................................................................... 108
Using html5 data-* attributes ............................................................................................... 109
Fetching images from the database ..................................................................................... 109
Calendar .................................................................................................................................... 109
Cross tabulation .......................................................................................................................... 116
Calculating column and row summaries ............................................................................... 118
Define the crosstab column header order ............................................................................ 120
Predefine data columns ...................................................................................................... 120
Full cross tabulation example .............................................................................................. 122
Header levels ............................................................................................................................. 123
Appearance ................................................................................................................................ 127
Pageview ............................................................................................................................ 129
Placing elements side by side ............................................................................................. 130
Creating an automatic row number ...................................................................................... 130
Adding additional column header group ............................................................................... 130
Set column sorting and override the default sorting method for a column ............................... 131
Disabling sorting on selected columns ................................................................................. 132
Search / export visibility ...................................................................................................... 133
Auto refresh ....................................................................................................................... 133
Set dynamic column title ..................................................................................................... 134
Show parameters within report ............................................................................................ 134
Use DIV's instead of tables ................................................................................................. 134
Paging result sets ............................................................................................................... 135
Using tabs to organize your report content .......................................................................... 135
Using accordions to organize your report content ................................................................. 137

vi
myDBR Documentation

Placeholder for nonexistent data ......................................................................................... 138


Sticky headers .................................................................................................................... 138
Lock leftmost columns ........................................................................................................ 138
Using column filters ............................................................................................................ 139
Resultset options ................................................................................................................ 139
Compare ............................................................................................................................ 140
Charts ........................................................................................................................................ 141
.......................................................................................................................................... 141
Explanation ......................................................................................................................... 141
Chart types: ........................................................................................................................ 142
How to create a chart? ....................................................................................................... 152
Setting own chart colors ..................................................................................................... 154
Chart options ...................................................................................................................... 155
Sparkline charts .................................................................................................................. 171
Chart examples .................................................................................................................. 172
Meter ................................................................................................................................. 184
Graphviz ............................................................................................................................. 187
Linked reports ............................................................................................................................ 193
Linked report parameters .................................................................................................... 196
Linked report placement ...................................................................................................... 196
Output destination of the linked report ................................................................................. 196
Optional links based on data ............................................................................................... 198
Examples ........................................................................................................................... 198
Buttons as links .................................................................................................................. 203
Select lists as links ............................................................................................................. 204
Lists as links ...................................................................................................................... 204
Searchable ......................................................................................................................... 206
Optional links ...................................................................................................................... 206
Editable reports .......................................................................................................................... 207
Passing HTML into the page ....................................................................................................... 223
Templates .................................................................................................................................. 225
Using full queries inside a template ..................................................................................... 230
Recording template variables .............................................................................................. 232
Running total .............................................................................................................................. 233
Import commands ....................................................................................................................... 235
Export commands ....................................................................................................................... 238
Remote calls to other myDBR servers ......................................................................................... 247
7. Extensions ...................................................................................................................................... 250
Overview .................................................................................................................................... 250
Processing the result set .................................................................................................... 250
JavaScript .......................................................................................................................... 251
extensions.php .................................................................................................................... 251
Extension example ............................................................................................................. 252
Dummy extension example ................................................................................................. 253
A passthrough extension ..................................................................................................... 253
Google Maps extension .............................................................................................................. 253
OpenStreetMap extension ........................................................................................................... 264
Mail extension ............................................................................................................................ 271
Usage ................................................................................................................................ 271
Push Notification extension ......................................................................................................... 273
Usage ................................................................................................................................ 275
eChart extension ........................................................................................................................ 276
Usage ................................................................................................................................ 276
d3 extension ............................................................................................................................... 277
SMS extension ........................................................................................................................... 279
Usage ................................................................................................................................ 280
Organization chart extension ....................................................................................................... 280
Barcode extension ...................................................................................................................... 286

vii
myDBR Documentation

QR code extension ..................................................................................................................... 288


8. Supported datatypes ....................................................................................................................... 291
MySQL ....................................................................................................................................... 291
Microsoft SQL Server, Sybase ASE, SQL Anywhere .................................................................... 292
9. Security .......................................................................................................................................... 294
10. myDBR SQL Editor ....................................................................................................................... 296
Editor basics ............................................................................................................................... 296
Query Builder ............................................................................................................................. 297
Building a query ................................................................................................................. 297
myDBR Commands .................................................................................................................... 298
Using SQL Editor ....................................................................................................................... 298
Executing statements .......................................................................................................... 299
Getting code for additional objects ...................................................................................... 299
Using autocomplete ............................................................................................................ 299
Output as SQL ........................................................................................................................... 299
Code snippets ............................................................................................................................ 300
Keyboard shortcuts ..................................................................................................................... 301
A. MySQL Stored Procedures ............................................................................................................. 303
Using parameters ....................................................................................................................... 303
Stored procedure without parameters .................................................................................. 303
Stored procedure with parameters ....................................................................................... 303
Using Variables .......................................................................................................................... 304
Using Conditions ........................................................................................................................ 304
IF-THEN-ELSE ................................................................................................................... 304
CASE ................................................................................................................................. 305
Using Loops ............................................................................................................................... 306
WHILE ... END WHILE ........................................................................................................ 306
REPEAT .. END REPEAT ................................................................................................... 307
LOOP .. END LOOP ........................................................................................................... 307
Using Temporary Tables ............................................................................................................. 308
B. Command reference ....................................................................................................................... 310

viii
Chapter 1. Welcome to myDBR

myDBR is a web-based reporting system for relational databases that allows you build a feature rich,
manageable and scalable reporting environment. myDBR manages the distribution and access rights
automatically, so it also scales well to large scale installations. Users are able to access reports using a web
browser, no additional software installations is required.

Fast and feature rich report authoring


When authoring a report, all your effort should be concentrated into the content of the report. myDBR helps you
to achieve this by taking away the unnecessary work needed in traditional reporting systems.

Browse through your data with report network


With myDBR you can easily link reports together allowing you to building a report network. This gives your
users a natural path for data mining and drill-down reports using business concepts close to them. Moving from
individual reports to a report network makes sure you are getting the most out of your data.

Automated distribution and access rights


By automating the distribution and access rights to reports, you can rest assured that the right people have the
right data at their disposal. You can easily connect the reporting system's access control mechanism to your
own data and automate access.

1
Chapter 2. Installation
myDBR is a PHP application which stores it's information (reports, report privileges, required database objects
etc.) into the database. In order to install myDBR, a working PHP environment with database support is needed.
myDBR is shipped as a compiled PHP application, for which a PHP loader is needed. myDBR also supports
optional modules which you may want to install.

Quick Start
The recommended way to install myDBR is by using the installation wizard which will check your environment
and set up myDBR for you in a matter of minutes.

1. Download the myDBR application from myDBR.com

2. Extract the downloaded mydbr.zip to the desired location on your web server

3. Point your favorite web browser to the location where you put the myDBR files

4. Follow the instructions provided by the installation wizard

5. You will be prompted to install the ionCube PHP loader if your environment does not have it installed

6. See also Optional installations

Installation complete - Enjoy using myDBR!

Manual Installation
myDBR installation requires following steps:

• A working PHP environment with database support. See Installation prerequisites.

• Database requirements

• PHP 5.x

• mysqli for MySQL support

• FreeTDS or Microsoft PHP drivers for Microsoft SQL Server

• FreeTDS for Sybase ASE or SQL Anywhere support

• myDBR application. See Installing myDBR application.

• Prepare the report database

• Install the PHP loader

• Installing myDBR application

• Optional installations

• Graphviz support for hierarchical and network charts (recommended, free). myDBR also uses Graphviz
internally (if installed) to show the report network structure.

• wkhtmltopdf for full quality PDF output

• Image chart support (commercial ChartDirector support). By default myDBR ships with the Flash chart
support (with the help of InfoSoft Global's nice FusionCharts Free) package
2
Installation

Installation prerequisites
myDBR installer will guide you to install the required component. Following setup is required for successful
installation of myDBR:

• A web server (Apache, IIS) with PHP installed

• PHP database extension for your database

• ionCube PHP loader

• MySQL, Microsoft SQL Server, Sybase ASE or SQL Anywhere database

PHP
Make sure that your PHP installation is in order. PHP 7.0 or greater is recommended. More information on
http://www.php.net.

ionCube PHP loader


myDBR is a compiled PHP application compiled with ionCube PHP compiler. In order to use the application the
ionCube PHP loader needs to be installed in your system (if not already present). When you access myDBR
without ionCube loader installed, myDBR will give installing instructions for the loader. You can also download
the ionCube Loader Wizard-script which gives you detailed information which loader to download and how to
install it.

You can download the loader from ionCube's download page.

Once a loader has been installed, so you can continue the myDBR install.

Database version requirement


MySQL: use database version 5.0.7 or greater. More information on http://www.mysql.com.

MariaDB: all versions are compatible with myDBR.

Microsoft SQL Server: use database version SQL Server 6.5 or greater. More information on http://
www.microsoft.com/sql/default.mspx.

Sybase ASE: use database version 15.0.2 or greater. More information on http://www.sybase.com/ase.

SQL Anywhere: use database version 11 or greater. More information on http://www.sybase.com/products/


databasemanagement/sqlanywhere.

Choosing the Database Driver


To choose the most suitable PHP database driver, use the following table:

PHP running on Windows OS PHP running on any other OS


MySQL mysqli mysqli
Microsoft SQL Server PHP 5.x: FreeTDS PHP 5.x: FreeTDS
PHP 7.x: PHP Linux Drivers for SQL Server PHP 7.x: PHP Linux Drivers for
SQL Server
Sybase ASE FreeTDS FreeTDS
SQL Anywhere FreeTDS FreeTDS

MySQL support: mysqli


For MySQL, PHP must have the mysqli extension enabled. For information on installation of mysqli, see http://
www.php.net/mysqli. Most PHP installations have this enabled by default.

3
Installation

Microsoft SQL Server with Windows PHP server


If you are running a Microsoft SQL Server and your PHP runs on Windows server, you can choose between
FreeTDS (php_dblib.dll) and Microsoft Drivers for PHP for SQL Server extension (version 4.0 supports PHP
7.0, version 3.2 supports PHP 5.6, 5.5, and 5.4, version 3.1 supports PHP 5.5 and 5.4 and version 3.0 supports
PHP 5.4.). Microsoft's extension is referred as 'sqlsrv' inside myDBR.

Microsoft provides also PHP Linux Drivers for SQL Server at GitHub for PHP 7.

Microsoft SQL Server, Sybase ASE and SQL Anywhere support: mssql + FreeTDS
If you are using Microsoft SQL Server (non MS PHP), Sybase ASE or SQL Anywhere a FreeTDS version of
mssql PHP extension is used. You can check the phpinfo.php output for the MSSQL Support string. myDBR
installation will check that the mssql-extension is installed. Do not use the old deprecated mssql-extension as
it is not supported.

Microsoft SQL Server, Sybase ASE and SQL Anywhere support


myDBR uses PHP's mssql (FreeTDS) extension to access Microsoft SQL Server, Sybase ASE and SQL
Anywhere. Usage of FreeTDS is required as with FreeTDS myDBR can use UTF-8 character set. Note that
if you are running Microsoft SQL Server and your PHP runs on Windows server, you can also choose to use
above mentioned Microsoft PHP Drivers.

FreeTDS configuration
Windows
Use php_dblib.dll instead of php_mssql.dll in the php.ini. php_dblib.dll c ontains the FreeTDS libraries needed
for proper character set (UTF-8) handling. A good source for the Windows php_dblib.dll extension is moodle.org

Other OS
Make sure you have FreeTDS installed and that your PHP installation has mssql-support enabled.

FreeTDS Configuration
To access Microsoft SQL Server, Sybase ASE or SQL Anywhere install FreeTDS libraries. FreeTDS
configuration is handled by the freetds.conf-file. You can check the location of the freetds.conf file by issuing
the command "tsql -C". If you are accessing only a single database server, you can make the configurations
under the [global]. If you plan to use FreeTDS to access multiple database servers, make the specifications
under a specific database server section.

SQL Server freetds.conf configuration:

[global]
client charset = UTF-8
text size = 2147483647
tds version = 7.2

The TDS protocol version depends on the SQL Server version you are using:

SQL Server version tds version


Microsoft SQL Server 2000 7.1
Microsoft SQL Server 2005 7.2
Microsoft SQL Server 2008 7.3
Microsoft SQL Server 2012 or 2014 7.4

Sybase ASE and SQL Anywhere freetds.conf configuration:

4
Installation

[global]
client charset = UTF-8
text size = 65536
tds version = 5.0

If you expect to handle longer text or images larger than 2K, change following php.ini-settings:

mssql.textlimit = 2147483647
mssql.textsize = 2147483647

myDBR expects the dates in the form of Y-m-d H:M:S, so check that your FreeTDS's locales.conf contains
following setting:

[default]
date format = %Y-%m-%d %H:%M:%S

In order to check the connection and the correct character set, use the tsql command to see what everything is
ok. You should be able to connect and see that the used charset is UTF-8 and your dates are correctly formatted
(your locale might vary):

$ tsql -Sserver -Uuser -Ppassword


locale is "fi_FI.UTF-8"
locale charset is "UTF-8"
1> select getdate()
2> go

2016-09-30 12:45:10
(1 row affected)
1>

Installing the myDBR application


In order to install the myDBR application manually you need to complete following steps. (Please note that
myDBR provides also an automated installation wizard. Launch the wizard by simply pointing your browser at
the mydbr-directory):

1. Download the application

2. Setup the database

3. Install the PHP loader

4. Install the application

Download the myDBR application


Download the myDBR application from the myDBR website. You will receive a zip-package containing the
application. Extract the files from the zip-package and place them under your web root.

Select database user for myDBR


When you launch myDBR for the first time, you will be asked for the username and password under which
myDBR operates. The username and the password provided need to have:

5
Installation

1. Full access to reporting database's objects (by default mydbr) - see picture below

2. Select access to the database which contains the actual data to be reported (user database) - see picture
below

myDBR application and database access

You can use your existing database account to access myDBR or create a new database account. Below is an
example of how to create a new myDBR user account 'mydbr' in MySQL.

$ mysql -uroot -p --default-character-set=utf8mb4


Enter password: ******
mysql> create user 'mydbr'@'localhost' identified by 'mydbr_password';
mysql> exit;

In SQL Server and in Sybase, create the database with owner 'mydbr' (or db_owner role) and grant users read
access to the actual database containing the data you wish to read from (either directly or via db_datareader-
role).

If you do not have permissions to create new users, you can use an existing user and assign the required
privileges (see later steps).

Prepare the report database


myDBR stores all the reporting information (reports, internal objects etc.) into a database. You can either install
them into a separate database (recommended) or if you only have access to one database, you can install
the items directly to the database you will be reporting from. All items in myDBR are named with '*mydbr*' to
separate them from the user's data and objects.

6
Installation

myDBR requires full access to the myDBR reporting database and select-access to the database you are
reporting from. See picture above. You can either use an existing database user or create a new one. In this
example installation we have created a user with name 'mydbr'.

Change to the db_creation directory (we'll use the database creation scripts):

$ cd install/db_creation

• For MySQL:

1. Create the mydbr database (or use any existing database):

$ mysql -uroot -p --default-character-set=utf8mb4


Enter password: ******
mysql> create database mydbr character set = 'utf8mb4';
mysql> exit

2. Add required privileges for the 'mydbr' user:

a. Full access to myDbr database and

b. Select-access to 'mydatabase'
As an example we have created a user called 'mydbr' and our data resides in the 'mydatabase' database.

$ mysql -uroot -p --default-character-set=utf8mb4


Enter password: ******
mysql> grant all on mydbr.* to 'mydbr'@'localhost';
mysql> grant select on mydatabase.* to 'mydbr'@'localhost';
mysql> exit

3. Create the mydbr reporting database objects:

$ mysql -umydbr -p --default-character-set=utf8mb4 mydbr <


mydbr_create_mysql.sql
Enter password: ******

If the creation script finishes without any errors, you are ready to move to next step.

• For Microsoft Sql Server:

1. Create a database called 'mydbr' with the Microsoft SQL Server Management Studio with 'mydbr' as the
owner

2. Create the database objects:

C:\>osql -n -U mydbr -P password -d mydbr < mydbr_create_mssql.sql

If you do encounter problems during the database creation, please check that you have sufficient privileges
for creating database objects.

7
Installation

• For Sybase ASE

1. Create a database called 'mydbr' with the Sybase tool with 'mydbr' as the owner

2. Create the database objects:

isql -Umydbr -Ppasssword -Dmydbr < mydbr_create_sybase.sql

If you do encounter problems during the database creation, please check that you have sufficient privileges
for creating database objects.

• SQL Anywhere:

1. SQL Anywhere uses one database model so the objects are created in a user database. Use a different
username (mydbr) to create the objects

2. Create the database objects:

isql -Umydbr -Ppasssword -Dmydb < mydbr_create_sybase.sql

If you do encounter problems during the database creation, please check that you have sufficient privileges
for creating database objects.

Note
The install script will create a myDBR admin (user inside myDBR) with a username/password dba/dba.
You should change the username/password as soon as you have installed the application.

Install the myDBR application


The last thing to be done is to move the unpacked mydbr-directory to your server root and change its
permissions.

1. Check your server root and copy the unpacked mydbr-directory into it.

2. Ensure that all the files are the have appropriate owner, i.e. the files are readable by the web server. See
the example below.

3. Make sure that the myDBR's configuration file config.php is writable to the web server. This allows the
admin to change myDBR's settings via browser. Also make sure that it is not readable to other users.

4. The first time you launch the application (point the browser to the myDBR web share), the application will
ask you for the connection information and formatting options. The username and the password asked in this
screen need to have ownership of the myDBR database and access to the reported data.

Example permissions on linux (check your document directory and apache user). On MacOS X the apache user
is by default "_www".

$ sudo mv mydbr /var/www/html


$ cd /var/www/html/mydbr
$ sudo chown -R apache:apache * .
$ sudo chmod -R go-r *
$ sudo chmod -R u+w *

Point your browser to http://localhost/mydbr/. If your installation is complete you are greeted with the setup
screen.

8
Installation

If you ever need to reset the install to this point, in the config.php you'll find a key 'SETUPDONE' which will
determine if the myDBR application will present the install screen or the normal login screen.

Installation wizard
The first time you use the application, you will be greeted by the install wizard. By this point you should be
able to enter the connection details to your reporting database. myDBR also makes system checks to see that
your environment is in working order. If you see error messages on screen, please fix the configuration errors
before proceeding.

Required fields
Database vendor Select the database vendor. myDBR uses native connection to each
database for maximum performance.

Host The computer where the reporting database is located. Hostname or IP


address.

Database The name of the database containing the mydbr objects.

Username The admin user's username. This user must have the privileges to mydbr
database object, including the right to execute stored routines. In the
example installation we created user mydbr for this purpose.

If myDBR will be configured in MySQL (at later stage), to use database


authentication, root access is needed. If the authentication is myDBR or
external application authentication, no root access is required.

Password The password for the admin user.

Use SSL When using MySQL, the traffic between web server and database server
can be secured with SSL. Checking this option will force the connection to
use SSL. You can additionally use certificates to limit connection to known
client / host.

Key File The client's private key (must be used with Certificate)

Certificate (must be used with Client certificate


Key File)

CA Cert The certificate authority certificate

Complete the setup and you should be ready log in with the default username dba and password dba. You
might want to change this after the setup is done.

Optional installations
Image chart support with ChartDirector

The myDBR Premium version of myDBR includes a license for the commercial ChartDirector charting module
from Advanced Software Engineering. The benefit of using the ChartDirector instead of the flash chart module
that ships with myDBR is the ability to produce the pictures without client side flash plugin, support for more
chart types, better support for printing and iPhone / iPod touch support for charts.

Both image and flash charts can be used simultaneously. Image and flash charts share the same syntax in
myDBR, so you can choose which one to use without changes to the actual report code.

To make best use of the myDBR Premium version download your copy of ChartDirector for PHP package from
the Advanced Software Engineering's website and follow the instructions. Once you have installed ChartDirector
to your system, myDBR recognizes it and you can set it as a preferred charting module (see Environmental
settings). The installation instructions are included in the download and you will find them also online.

9
Installation

wkhtmltopdf - recommended

myDBR supports wkhtmltopdf if installed on the server. wkhtmltopdf uses the Webkit rendering engine to convert
content to PDF. Using wkhtmltopdf enables pixel perfect PDF reports generated from the server side therefor
allowing things like forms to be generated.

If wkhtmltopdf is not installed on the server, myDBR uses an alternative PDF output method. However installing
wkhtmltopdf is recommended. To install wkhtmltopdf, follow the instructions on the wkhtmltopdf website.
wkhtmltopdf will be installed as a command line tool and should be found in the PHP path. If it cannot be
added to a PATH variable, a direct link to the command can be given in mydbr/user/defaults.php by setting the
$mydbr_defaults['export']['wkhtmltopdf']['command'] variable to a full path to the command.

Example if wkhtmltopdf is not found in PHP's PATH:

$mydbr_defaults['export']['wkhtmltopdf']['command'] = '"C:\Program Files


(x86)\wkhtmltopdf\wkhtmltopdf.exe"';

Once you have installed wkhtmltopdf to the server, go to 'Environment settings' and see the 'Installed modules' if
PHP is able to see the program. If not, you may need to define the full path to the command in $mydbr_defaults.

Graphviz support
Graphviz adds support for the hierarchical and network charts. myDBR also uses Graphviz internally (if installed)
to show the report network structure. In order to take advantage of Graphviz charts, the basic package for
Graphviz and the PEAR Graphviz-package needs to be installed.

1. Graphviz Download and install the latest Graphviz support from http://www.graphviz.org/Download.php for
your environment.

2. PEAR Download and install latest version of PEAR

3. Image_GraphViz PEAR package. Install the PEAR Graphviz-package (1.3.0 is the latest one as of this
writing)

$ sudo pear install -f Image_Graphviz-1.3.0

More information about PEAR package installations.

Update myDBR
New versions of myDBR are released regularly. If your server has a connection to mydbr.com, an update
notification is shown when a new major version is available. It is recommended to run the updater once new
versions are introduced. The new versions can contain bug fixes and new functionality. Updates are designed
to keep existing report running as is.

Automatic updater using web interface


The preferred update method for myDBR is to use the built-in automatic update method. myDBR periodically
checks if new version is available and it will notify the admin user in the main page of the new versions. At
any time, if you wish to update myDBR, you can invoke the update from Admin Tools -> About / Update -
> Update now... . If your license has expired and you cannot see the Admin Tools-section, you can click on
myDBR-logo in top left corner to bring up the "About / Update"-dialog.

While carrying out the automatic update, myDBR replaces the application itself and updates the myDBR
reporting database to include the latest changes. All the reports will be kept intact. Also, any modifications to
user settings under user-directory are kept (this includes user specific logos, settings etc.).

10
Installation

If your server is behind a proxy and is not able to contact the myDBR update server, the proxy settings can be
entered in the Environment settings. If you are unable to update myDBR even with the correct proxy settings,
please see that you have php_curl installed.

Manual update
If your server does not have a connection to mydbr.com (direct or through a proxy), manual update needs to
be applied. To perform a manual update, do following:

• Save possible changes made to the myDBR configuration by saving the mydbr_config.php (contains the login
information to the database) and any changes made in /mydbr/user-directory

• Download the myDBR zip package from http://mydbr.com

• Replace the existing myDBR install with the new unzipped content of the zip-package

• Restore the saved mydbr_config.php and any changes made to /mydbr/user-directory

• Access myDBR through the web server

myDBR will now see the updated application and will guide through the rest of the installation through the update
wizard. All your reports will stay intact.

Scripting the automatic updater


The automatic updater can also be scripted.

To get the current version as JSON, run following URL:

% curl "https://myserver.mydomain.com/mydbr/index.php?a=version&export=json"

The result for the version query will be:

{
"version":"4.3.2",
"build":"2534"
}

The version query URL also supports JSONP, so if you query type is jsonp and you add callback parameter
to the query:

% curl "https://myserver.mydomain.com/mydbr/index.php?
a=version&export=jsonp&callback=mycallback"

The result for the version query will be:

mycallback(
{
"version":"4.3.2",
"build":"2534",
"key":"bfb61ab9c7"
}
);

The key will be last 10 characters of your license. You can use this in your script to verify that the server is
using the lastest license.

11
Installation

When the update URL (see example) is called, authentication is carried out using HTTP basic access
authentication. myDBR defines, by default, username 'mydbr_updater' to be used with scripted updates. This
is defined in defaults.php and can be overridden in mydbr/user/defaults.php.

To activate the username (mydbr_updater) to be used in scripts, the username needs to be added to myDBR
users. Usernames defined as updater-usernames are limited to the update function only and cannot therefore
be used as normal login users.

The update URL is called using basic access authentication (replace the myserver.mydomain.com/mydbr with
your own definition):

% curl -H "X-MYDBR-AUTH: 1" -u mydbr_updater:mydbr_updater_password "https://


myserver.mydomain.com/mydbr/install/index.php?controller=update&action=update"

The result for the updater is a JSON object with following fields:

If there was an error in the update process, an "error" entry will be added to the JSON object. The entry has
the error message that caused update to fail.

{
"host":"myserver.mydomain.com",
"expiration":"2015-12-22",
"version": {
"before_update":"4.3.2\/2534",
"after_update":"4.4.0\/2697"
}
}

The update URL supports also JSONP, so you can use the call in a report's JavaScript. To use JSONP-include
the 'callback'-parameter to the URL.

% curl -H "X-MYDBR-AUTH: 1" -u mydbr_updater:mydbr_updater_password


"https://myserver.mydomain.com/mydbr/install/index.php?
controller=update&action=update&callback=mycallback"

mycallback({
"host":"myserver.mydomain.com",
"expiration":"2015-12-22",
"version": {
"before_update":"4.3.2\/2534",
"after_update":"4.4.0\/2697"
}
});

Scripting the license installation


The most common way of installing the license is just to copy/paste the license into the license view. However,
if you have large number of installations, you might want to script the license installation. In this case you define
one of the installations as license server and other servers fetch their licenses from this server. To get the
licenses into the license server, you can copy/paste all purchased licenses at once, if you copy the licenses
under the 'Copy all licenses'-link in myDBR Shop's order HTML page (https://shop.mydbr.com/index.php?
a=order&a=order&id=XXX).

To define an installation as license server (a server which will contain the latest license and serve those to other
servers per request), set the server status to true in user/defaults.php and create a license server user
into myDBR (by default 'license_checker', can be overriden in the defaults)-

12
Installation

$mydbr_defaults['license_server']['is_server'] = true;

To let the client server know the existence of the license server add the following to the client servers user/
defaults.php (can be the same for all clients).

$mydbr_defaults['license_server']['server_url'] = 'https://myserver.mydomain.com/mydbr';

To issue a license retrieval call to client use syntax:

% curl -H "X-MYDBR-AUTH: 1" -u license_checker:license_checker_password "https://


myclient.mydomain.com/mydbr/index.php?a=license_service&update=1"

When the call was successful, the response will be:

{"status":"ok"}

If there is a problem with the call, the response will look like:

{"success":"error" errors = {"array of errors"}}

Again, this URL also supports JSONP with the additional 'calback'-parameter to the URL.

Managing large number of installations


When managing large number of installations, you can automate the license installing and upgraging process.
You can either use scheduled report in clients to ask for new licenses and script the updates or you can use a
report to manage license distribution and server updates.

Automating license distribution


A sample report running on defined license server. It fetches the version and license information from the client
servers and allows remote license distribution and version updates. With the report you can handle large number
of servers from one interface without need to login to individual servers.

create procedure sp_DBR_update_license(


inVersionBuild varchar(20)
)
BEGIN

select 'dbr.css', '


.license_status {
text-align: center;
}
.license_update, .version_update {
cursor: pointer;
background-color: green;
padding: 3px 6px 3px 6px;
border-radius: 6px;
color: white;
}
.red {
background-color: red;
}
.version {
text-align:center;

13
Installation

}
.version .ajaxspin {
margin: auto;
}
';

select 'dbr.colclass', 'host', 'host';


select 'dbr.colclass', 'license_status', 'license_status';
select 'dbr.colclass', 'version', 'version';
select 'dbr.colclass', 'errors', 'errors';
select 'dbr.html5data', 'host', 'license_key', 'license-key';
select 'dbr.html5data', 'host', 'license_host', 'license-host';
select 'dbr.html5data', 'version', 'version_build', 'version';

select
concat('https://', host) as 'Installation URL[host]',
l.host as 'license_host',
l.license_key,
'' as 'Version[version]',
'' as 'License OK[license_status]',
inVersionBuild as 'version_build',
'' as '[errors]'
from mydbr_licenses l
where host != 'mylicenseserver.mydomain.com';

select 'dbr.javascript',
"$(document).ready(function() {
// Get installed versions and last 10 characters from the installed license
$('.host').each( function() {
var $tr = $(this).closest('tr'),
url = $(this).text()+'/index.php?a=version&export=jsonp&callback=?';
$.ajax({
url: url,
dataType: 'jsonp',
success: function(v) {
// Query returns 10 last characters from the license. Enough for the matching
var $v, vb, key_ok = (v.key == $tr.find('.host').attr('data-license-
key').substr(-10));
$v = $tr.find('.version');
vb = v.version+'/'+v.build;
if ($v.data('version') !== vb) {
$v.html('<span class=\"version_update\">'+vb+'</span>');
} else {
$v.text(v.version+'/'+v.build);
}
if (key_ok) {
$tr.find('.license_status').text('OK');
} else {
$tr.find('.license_status').html('<span class=\"license_update\">Newer license
available</span>');
}
},
error: function(e, status, error) {
$tr.find('.version').text('Unknown');
$tr.find('.errors').text(e.status+'/'+error);
}
});
});

// Ask the installation to update the license from the license server
$(document).on('click', '.license_update', function() {
var url, $tr = $(this).closest('tr');
url=$tr.find('.host').text()+'/index.php?a=license_service&update=1&callback=?';
$.ajax({

14
Installation

url: url,
beforeSend: function(xhr) {
xhr.withCredentials = true;
xhr.setRequestHeader('X-MYDBR-AUTH', '1');
xhr.setRequestHeader('Authorization', 'Basic ' + btoa('license_checker:pass'));
},
dataType: 'jsonp',
success: function(r) {
var i,e='';
if (r.status=='ok') {
$tr.find('.license_status').text('OK');
} else {
$tr.find('.license_status .license_update').addClass('red');
for(i=0; i<r.errors.length; i++){
e += '<div>'+r.errors[i]+'</div>';
}
$tr.find('.errors').html(e);
}
},
error: function(e, status, error) {
$tr.find('.errors').text(e.status+'/'+error);
}

});
});

// Ask the installation to run the updater


$(document).on('click', '.version_update', function() {
if (confirm('Update version?')) {
var url, $tr = $(this).closest('tr'), $v = $tr.find('.version');
url=$tr.find('.host').text()+'/install/index.php?
controller=update&action=update&callback=?';
$v.html('<div class=\"ajaxspin\"></div>');
$.ajax({
url: url,
beforeSend: function(xhr) {
xhr.withCredentials = true;
xhr.setRequestHeader('X-MYDBR-AUTH', '1');
xhr.setRequestHeader('Authorization', 'Basic ' + btoa('mydbr_updater:pass'));
},
dataType: 'jsonp',
success: function(r) {
if (r.error) {
$v.text(r.error);
} else {
if (r.version.after_update) {
$v.text(r.version.after_update);
} else {
$v.text('Unknown error');
}
}
},
error: function(e, status, error) {
$tr.find('.errors').text(e.status+'/'+error);
}
});
}
});

});
";
end

15
Installation

How does myDBR access the database?


myDBR was designed to be a reporting system that can be used without any modifications to the actual user
databases. By default myDBR installs into it's own reporting database ('mydbr' by default). All myDBR database
objects (including reports) are stored in this database. myDBR only needs read access to the database where
the actual data is held.

You can also install myDBR directly to the user database, where your data is (instead of the default mydbr).
myDBR uses its own naming scheme, so it will not conflict your data. (myDBR objects have a prefix of: "mydbr_"
for tables, "sp_MyDBR_" for myDBR internal procedures, "sp_DBR" for report procedures).

myDBR database access can be divided into two parts: login process and the report execution. Here we'll go
through both of them.

User login
In the login process myDBR checks if the user has credentials to log in to the system. By default myDBR uses
it's internal structure to hold usernames/passwords. Following authentication modules are available in myDBR
preferences:

myDBR user authentication Users username and password hash are checked against the
myDBR's internal structure (mydbr_userlogin-table). The password field in
mydbr_userlogin-table is an md5 hash of the actual password.

Database login Users username and password are used for an single log in to the database
system. The user is allowed to log in and his/her username/password can
be used to log in to the database.

Single Sign-On Users username and password are checked against external applications
authentication. Please see more info at Single Sign-On

Active Directory Users username and password are checked against Microsoft Active
Directory.

Custom Suitable for environments where authentication is handled by external


service, but Single Sign-On will not be suitable. In Custom authentication,
user enters username / password in myDBR and myDBR connects

16
Installation

external service to do authentication and to report user/group info.


Custom authentication provides very easy integration of myDBR to external
server. The authentication implementation will be done in mydbr/user/
custom_authentication.php where the protocol is documented.

If you want to allow the use of myDBR without any login process (public intranet, extranet), you can set automatic
login credentials in Admin preferences. When automatic logins are set, admin access can be gained by pointing
the browser to login.php instead of the usual index.php.

17
Installation

Report execution
Once the login process has been completed, all the operations in the database are done using the username/
password stored in the admin preferences (section Database connection info: Username/Password). These
are stored in the config.php (entries admin_username and admin_password). These are referred here as
'myDBR credentials'. myDBR credentials must have full access to the mydbr-database and read access to the
user database objects.

Report creation

The reports are created in the mydbr-database as stored procedures. myDBR credentials must have execution
access to these stored procedures. When accessing the data in the actual user database one refers to tables
using format 'mydatabase.mytable' in MySQL and 'mydatabase..mytable' in MS SQL Server, Sybase
ASE.

SQL Anywhere does not support multiple databases so reports are created in same database. As an alternative,
you can install myDBR in a separate database and use SQL Anywhere proxy tables to link your data tables.

myDBR License
myDBR requires a license for each myDBR installation. The myDBR server is identified by its host name /
installation path. You can get the license from myDBR shop.

Requesting a license
You can request new licenses and manage your existing licenses from the myDBR shop. myDBR will
automatically provide you with a link to request a license if it cannot find a valid license for your server.

Once you have received your license via e-mail, copy the text between the --- clip lines to the setup screen
or the Licenses tab of myDBR.

If myDBR does not accept your new license, make sure you have updated myDBR to the latest version. See
Update myDBR for more info. myDBR licenses are always generated for the latest version.

How many licenses do I need?


You will need a separate license for each myDBR instance you are running.

Let's assume that you have installed myDBR on your workstation, so you would usually access the solution via
the URL http://localhost/mydbr. Therefore you will need a license for the domain localhost. If you
then deploy myDBR to your production server with the URL http://www.myserver.com/mydbr you would
need another license for the domain www.myserver.com

Information contained in the license


The license you receive via e-mail contains the following information:

Owner The name of the person to whom the license is registered

Mail The e-mail address of the owner

Host The host name under which myDBR is accessed. If you have myDBR installed at http://
reports.mycompay.com/mydbr the host is reports.mycompay.com. If you are using nonstandard
port, include the port to hostname.

Company The name of the company where myDBR is installed

DB The type of database used

Expiration The date when the license expires, in YYYY-MM-DD format. For example 2010-11-30 means
30th November 2010

18
Installation

Type The type of the license

Version The minimum version of myDBR required to use this license. If your installed myDBR version
is to old, you will need to update first

Key The license key generated for you by the myDBR Team

A license looks like this:

----- clip
owner=John Smith
mail=john.smith@mycompany.com
host=reports.mycompay.com
company=My Company Ltd.
db=mysql
expiration=2017-11-30
type=premium
version=4.9.0
key=4e03204ad1092905a59e099f8ie2e3fed813cf6952ee133fda11f906744ef6c2
----- clip

19
Chapter 3. Getting started
Creating your first report
myDBR reports are database native stored procedures that you can create using the built in SQL Editor (or any
SQL editor that you prefer). For more details see myDBR SQL Editor.

To create a report, you will create a stored procedure in the myDBR database. The report stored procedure
has a prefix ('sp_DBR') which helps myDBR to differentiate report procedures from other procedures in the
database. Once the procedure has been created, it will be attached to the myDBR application's report hierarchy
via 'Add report' function. When attached, the report is ready to run.

Once the report has been attached to the myDBR structure, you are free to edit (or drop/recreate) the stored
procedure behind it. This allows maximum flexibility when developing your reports.

In addition to normal SQL data queries, myDBR reports include myDBR commands which are interpreted by
myDBR when the report is run.

First report
As an example, we'll write a simple report and go through the steps needed to use myDBR. The setup used in
the example is the default setup where user has the data in his/hers own database (called 'mydb') and myDBR is
using its own reporting database ('mydbr'). The examples are partly based on MySQL sample database Sakila.
If you wish to try out myDBR with Sakila-database, please follow the link and download it.

The first report will list films from the table 'film' from the user database 'mydb'. (We'll add up features to the
report later).

We'll write a stored procedure called sp_DBR_FilmList that will show the films in the database. 'sp_DBR' is the
default prefix for the report procedures. myDBR will use this prefix to assist you when you attach the stored
procedure as a report in the myDBR structure (i.e. distinguishes the report from other stored procedures in
the database). In the example we'll create the report by using the built in SQL editor and store it to the mydbr
database.

1. Click 'Add report' from main screens Admin tools.

If no unassigned stored procedures (procedures starting with 'sp_DBR' that are not used in report) can be found,
myDBR asks for the procedure name to be created:

2. Enter the procedure name and click OK.

myDBR will create you a template report into which you will add your queries and logic.

If you want to browse the database structure or get help with writing the SQL code, you can open the Query
Builder by clicking the "Show Query Builder"-button. You can pick the database, table and columns you wish to
be included in the report. Please see more ino on myDBR SQL Editor.

20
Getting started

3. Create a new procedure by using the Query Browser or by editing the code manually.

1. Select database

2. Select table

3. Select columns

4. Click 'Generate SQL into selection'

5. Edit procedure if necessary and click 'Execute' to save the procedure

You'll notice that we are giving each column a name which the user sees as column header in the report when
the report is run. If you do not specify the name, the name is derived from the column/data used.

Assign the report to the myDBR report structure

Click 'Execute' to save the report procedure to the database. If there were any errors, fix them and click 'Execute'
again. Once the report's stored procedure is successfully saved into the database, click the "Add report to
myDBR" button to attach the procedure as a report in myDBR's report structure.

21
Getting started

myDBR will fetch all the procedures from the database which match the prefix mentioned earlier and that have
not yet been assigned as a report. The report name is the name visible to the user, and the description shows
up in the report listings. After we accept the data, the report will be assigned to myDBR and is ready to be used.

For your convenience, myDBR opens up a screen where you can name the input parameters and grant privileges
to the report. We'll skip this for now and go back to main screen.

You should now be able to see the report in the main screen and run it.

The report has a title, which, by default, is the same as the report's name. If you wish to change the title in the
report (for example add dynamic data/parameters to it) you can use the command dbr.title to achieve this. By
default, myDBR makes columns sortable, just click on a header column to sort the data.

22
Getting started

Adding parameters to a report


We'll extend the report by adding parameters to the report. Report parameters are normally stored procedure
input parameters. By default, myDBR uses stored procedure parameters 'as is', but myDBR can also further
extend the parameters by:

• Naming the parameters

• Providing assistance based on data type (date pickers)

• Using predefined lists as parameters (as radio buttons, select lists)

• Using live autocomplete fields from the database (AJAX autocomplete)

• With linked reports automatically fill in parameters based on user input / report flow

In this example we'll set a film name (or part of it) as a parameter. We'll introduce a parameter 'in_film_name'
into the stored procedure.

create procedure sp_DBR_FilmList( in_film_name varchar(30) )


begin

select title as 'Title',


release_year as 'Release Year',
rental_rate as 'Rental Rate',
length as 'Length'
from mydb.film
where title like concat('%', in_film_name, '%');

end

Since the stored procedure has already been assigned to myDBR, we do not need to reassign it. Just edit the
procedure and you are ready to run it. Now when you re-run the report, the parameter is asked from us as
an input:

The variable name is not necessarily the name you want the user to see. Let's create a more descriptive name
for it. We'll go back to the main screen and edit the report's data by clicking the 'edit'-link below the report.

You'll go the screen where you can edit the ready filled basic data about the report, handle the parameters and
assign privileges to the report. We'll just give a name to our parameter.

23
Getting started

When we re-run the report we'll see that the new name for the parameter is used.

In order to learn how to use more advanced features on parameters, please consult the Managing Reports /
Report Parameter for further info.

Cross-tabulation report
In cross tabulation the result set's data is divided into header and data sections divided by a cross tabulation
column. Header columns, left from the cross tabulation-column (and optionally also on the right) will determine
the distinct rows in the final result set and the data columns will be repeated under distinct values under values
derived for the cross tabulation-column.

The purpose in cross tabulation is to turn the table from this:

into this:

When using cross tabulation, the order of the rows in the report will be determined by the order of the data in
the query. Similarly the order of the data columns are determined by the order of the data in the query. If you
want the data columns to appear in certain order or you data may not contain all the data columns, you can use
dbr.crosstab.col-command to predefine the data columns.

24
Getting started

Understanding the data parts in a cross-tabulation report

Say we have a basic data set:

select RepArea as 'Reporting area',


Period,
last_year as 'Last year',
this_year as 'This year',
next_year as 'Next year'
from mydb.ProductionSummary;

We can determine the different parts of the result set:

By defining the column 'Period' as a cross tabulation column, the distinct values in that column are calculated
as group columns and the data columns are calculated underneath each group column.

If any other column contains myDBR commands, they are automatically handled. In the example we'll use style
and some aggregate functions in data columns.

/*
Define the Period as a cross tabulation column
Make sure you remember to order the result set accordingly
*/
select 'dbr.crosstab', 'Period';

/* Highlight the current year */


select 'dbr.colstyle', 'this', mydbr_style('Diff colors with bg');

/* Calculate sums */
select 'dbr.sum', 'last','this','next';

select RepArea as 'Reporting area',


Period,
last_year as 'Last year[last]',
this_year as 'This year[this]',
next_year as 'Next year[next]'
from mydb.ProductionSummary;

25
Getting started

See full description of Cross Tabulation command.

Creating your first chart


myDBR allows you to generate different kinds of charts based on your data. For complete documentation on
charts see the Charts section. In this example we'll generate a sample pie-chart.

Generating a chart
As with the previous examples, we'll generate a stored report to generate the report and the data needed for
the chart. In case of a pie-chart, we need a caregory and value column. We'll create a sample Pie-chart of total
sales of the film categories. The procedure to be created looks like this:

create procedure sp_DBR_FilmByCategoryChart()


begin

select category, total_sales


from mydb.sales_by_film_category;

end

After we assign the procedure to myDBR and run it, we'll get the data needed for the chart. First parameter is
the chart type ('pie') and the second parameter is an optional chart name. You can also specify the chart size
or use any of the options available.

To generate a chart, a dbr.chart -command is added in front of the result set.

26
Getting started

create procedure sp_DBR_FilmByCategoryChart()


begin

select 'dbr.chart', 'Pie', 'Sample Pie chart';

select category, total_sales


from mydb.sales_by_film_category;

end

When we re-run the report, we'll get the data drawn as a chart.

For complete documentation on charts see the Charts- and Graphviz-section.

Pageview report
Pageview allows you to view the data in a 'record' format. It is mostly used in cases where you have only one
data row to be displayed. Instead of showing the data as a row, the format shows the data in a more readable
'record' -format (see picture below).

If we have a report that returns a single row the result might look something like this:

If the result contains multiple columns, it might be better to change the layout to use the Pageview-feature. We'll
place the command select 'dbr.pageview'; in front of the actual dataset query to turn the following result
set's columns into rows. So adding the command:

select 'dbr.pageview';

select f.title as 'Title',


f.description as 'Description',
f.release_year as 'Release year',

27
Getting started

f.rating as 'Rating',
l.name as 'Language'
from mydb.film f
join mydb.language l on f.language_id=l.language_id
where f.film_id = vID;

produces a result like this:

If the report produces multiple rows, each row is displayed as an individual record.

User Parameters
myDBR reports can have parameters that will be asked from the user when the report is run. The parameters
are the parameters for the stored procedure containing the report. Parameters can be any of the following:

Parameters can have default values which are used if user runs the report the first time. On subsequent runs,
parameters contain the last value used unless the parameter is set not to remember user's choises.

Parameters can be any of the following:

Basic fields

Date picker

Default values

Select lists

Radio buttons

Checkboxes

Autocomplete fields

Connected parameters

Automatic parameters

Parameters in linked reports

If nothing is pre-defined myDBR reads the stored procedures parameters (name and type) and simply asks the
values from the user. myDBR checks the datatype of the parameter and adapts the input field accordingly.

Basic fields (text/number)


Basic parameters in the report are requested as is from the user. myDBR allows the parameter name to be
changed, so instead of using the actual procedure parameter name, admin can assign a title for the parameter.

28
Getting started

In this example we'll use a film name (or part of it) as a parameter. We'll introduce a parameter 'in_film_name'
into the stored procedure.

create procedure sp_DBR_FilmList( in_film_name varchar(30) )


begin

select title as 'Title',


release_year as 'Release Year',
rental_rate as 'Rental Rate',
length as 'Length'
from mydb.film
where title like concat('%', in_film_name, '%');

end

Since the stored procedure has already been introduced as a report, we do not need to reassign it. Just edit the
procedure and you are ready to run it. Now when we re-run the report the parameter is asked from us as input:

The variable name is not necessarily the parameter name that you want to use. Let's create a more descriptive
name for it. We'll go back to the main screen and edit the report's data by pressing the Edit-button

next to the report.

You'll get the screen where you can edit the ready filled basic data about the report, handle the parameters and
assign privileges to the report. We'll just give a name to our parameter.

When we re-run the report we'll see that the new name for the parameter is used.

29
Getting started

Date picker
When the report parameter is a date or a datetime, myDBR automatically offers a date picker to the user to
make up the data entry easier. The date format used is defined in user's preferences.

If we have two consecutive dates as a parameter, one can treat them as date range (from-to), by checking the
'Keep the next parameter in same row' checkbox for the first date's option (Edit report -> Report Parameters ->
Other). myDBR will then automatically add a date range select list from which user can select the most common
date ranges (last week, last month etc).

create procedure sp_DBR_FilmUpdates( vStartDate date, vEndDate date )


begin

select title as 'Title',


release_year as 'Release Year',
rental_rate as 'Rental Rate',
length as 'Length',
last_update as 'Last Update'
from mydb.film
where last_update between vStartDate and vEndDate;

end

When we run the report, we are asked about the dates with the assistance of a picker:

myDBR shows the time in the picker if the datatype contains time elements (datetime).

Default values
A report's parameters can have default values. These values are used when the report is run the first time.
On subsequent runs, the default values are the ones the user used during the last run (unless the parameter
preference is set to not to remember user's choises). Default values are defined in the 'Admin->Parameter
queries'-page.

Let's examine the myDBR statistics report's defaults. The report has two date fields; one for the start time and
one for the end time. By default, myDBR offers to run the statistics for the past month with the start time by
default to be one months back from now. The default query is defined in 'Admin->Parameter queries' page:

30
Getting started

The defined defaults are then associated with the query parameters in the 'Edit query' screen:

When the report is run for the first time, the report's date fields defaults to the set default dates.

Predefined / dynamic parameters


In addition to simply requesting parameters from the user, myDBR allows one to present choices to the user.
These choices can be static or dynamic. In the latter case the choices are read from the live data. These choices
can be presented to the user as via a select list, radio button or an Ajax-style autocomplete field. The one to
choose depends on the data and the amount of choices available. A radio button is most suitable for limited
numbers of choices, a select list when there are more, but still a limited number of choices and finally the
autocomplete which can initially have a bigger selection.

Predefined / dynamic parameters are defined in the myDBR preferences (Admin->Parameter queries). These
are parameter queries that can be shared among all the reports. Parameter queries should return:

• The select list - id and user visible value

• The radio button - id and user visible value

• The autocomplete field - visible value

• The checkbox - id and user visible value

31
Getting started

Select lists
In order to convert a report parameter into a select list with different choices, we'll define the select list parameter
query in the 'Admin->Parameter queries'-page. The select list consist of a list of ID's and visual values for the.

A Select list parameter query can return following result set with some optional columns:

ID [, Visible value to user[, Grouping, [ 'selected' [, optional columns for


sorting]]]]

If the query returns just one column, the same column will be used for both ID and as the value visible to user. If
the group for the row is returned the values belonging to same group will be grouped with the HTML selectlist's
optgroup. If the fourth column of the parameter query is 'selected', that item will be chosen as the default.
This is especially useful if place the parameter query into a stored procedure and use automatic parameters
to customize the query.

As an example, we'll create a report which will list films based on a selected film category. In this example the
user can also to choose to show the full film list. We'll use the parameter inCategory so that when it equals
zero, well show all films, in other cases we'll show just the selected category.

create procedure sp_DBR_FilmsByCategory( inCategory tinyint )


begin

select f.title as 'Title',


f.description as 'Description',
f.release_year as 'Release year',
f.rating as 'Rating'
from mydb.film f
where f.film_id in (
select film_id
from film_category
where category_id = inCategory or inCategory = 0
);

end

We'll then prepare the select list with query that returns the id and the user visible value.

32
Getting started

The parameter query is then attached to the report in the 'Edit query' screen. We can at same time name the
parameter:

When we now run the report, a select list with predefined values is shown:

If a select list parameter query returns a column (fourth colum or greater) with title 'parameter_info', the data for
that column will be shown as info text for that selection. The column can contain HTML.

create procedure sp_param_info()


begin

select 1, 'First', '', 'Internal price: 200<br>External price: 300' as 'parameter_info'


union
select 2, 'Second', '', 'Internal price: 250<br>External price: 320'
union
select 3, 'Third', '', 'Internal price: 300<br>External price: 380';

end

Radio buttons

The radio button-parameter works exactly the same way as in the select lists. We'll create a radio buttons
showing just simple Yes/No selection:

33
Getting started

The radio button parameter query can return following result set:

ID [, Visible value to user]

If the query returns just one column, the same column will be used for both ID and as the value visible to user.

Let's create a simple report procedure that uses the defined radio button:

create procedure sp_DBR_YesNoParam( inYesNo tinyint )


begin

select inYesNo;

end

When we now run the report, a radio button selection is shown:

34
Getting started

Checkboxes

Checkboxes differ from other parameters in a way that multiple ID's are sent to the report. myDBR does this
by delivering a comma separated list of the selected ID's to the report. Report will parse the comma separated
list (examples below) and use the ID's as part of query.

The checkbox parameter query can return following result set:

ID [, Visible value to user[, Grouping, [ 'checked' [, optional columns for


sorting]]]]

If the fourth parameter is 'checked', that choise will be checked by default. This is especially useful if place the
parameter query into a stored procedure and use automatic parameters to customize the query.

We'll start by defining the checkbox choices in the 'Settings->Parameter queries'.

select category_id, name


from mydb.category;

When user selects multiple choises, a comma separated string of ID's is sent to report procedure ("1,2,4,10").
If the ID is a string (or date/datetime) the ID's are strings separated by comma ("'First','Second','Last'").

The defined parameter query is attached to the following report. The report will convert the comma separated
list to a table of ID's which can then later in the report be joined to other objects. The conversion will be done by
a prepared statement. This example is using MySQL and it takes advantage of MySQL's find_in_set-function.

create procedure sp_DBR_checkbox(


inCheckbox varchar(255)
)
begin

select category_id as 'User choice'


from category
where find_in_set(category_id, inValue);

end

Comma separated list parsing Microsoft SQL Server 2016 and above can be done with STRING_SPLIT-function.
In older versions one can by use the sp_executesql-system procedure. In Sybase ASE and in SQL Anywhere
you can use EXECUTE statement.

IF object_id('sp_DBR_checkbox','P') IS NOT NULL


DROP PROCEDURE [sp_DBR_checkbox]
GO
create procedure sp_DBR_checkbox
@inCB varchar(200)
AS
BEGIN
declare @sql nvarchar(200)

create table #data_tmp (


id int
)

select @sql = 'insert into #data_tmp select category_id from category where category_id in
('+@inCB+')'

35
Getting started

exec sp_executesql @sql

select id
from #data_tmp

drop table #data_tmp

END
GO

Autocomplete fields

Autocomplete fields narrow the selection by performing live queries on the database based on user data entry.
The user is presented with a simple entry field, and while the user enters the data into the field, suggestions
based on actual data are offered to user. The returned suggestions can be freely defined ('start of string'-match,
'contains'-match etc.). The actual definition for fetching SQL is different from the select list or the radio button.
The parameter defining the SQL must be a stored procedure and it will return the matching value and optionally
a additional description and ID(s) of the matching row.

One-line autocomplete

We'll create a report that returns film information. The selected film is fetched with an autocomplete film's field.
First we'll define the report showing the film info:

create procedure sp_DBR_FilmInfo( inFilmname varchar(30) )


begin

select 'dbr.pageview';

select f.title as 'Title',


f.description as 'Description',
f.release_year as 'Release year',
f.rating as 'Rating'
from mydb.film f
where f.title = inFilmname;

end

Next we'll create the autocomplete procedure, which takes one parameter (the user input) and it returns the
matched film names. This procedure is called every time the user enters data into the parameter field. In this
example the autocomplete matches from the beginning of the film title:

create procedure sp_Autoc_DBR_Titles( inTitle varchar(255) )


begin

select Title
from mydb.film
where Title like concat( inTitle, '%');

end

The autocomplete procedure is then added as a parameter query:

36
Getting started

Attaching the autocomplete parameter is done in same way as in select lists and the radio buttons:

When we now run the report, the parameter fields autocompletes the user input:

Two-line autocomplete
It is possible to display two lines of information in the autocomplete list. The first line contains the data that is
put into the input field after the user selects the row, the second line is there for more information. The second
line is generated by altering the autocomplete stored procedure by adding another column to the result set.

create procedure sp_Autoc_DBR_Titles( inTitle varchar(255) )


begin

select Title, special_features


from mydb.film
where Title like concat( inTitle, '%');

end

37
Getting started

When we now run the report, the parameter fields autocompletes the user input using both values:

Getting the IDs of the selected autocomplete value

If the autocomplete stored procedure returns more than two columns (matching selection and description
being the first two), the rest of the values are treated as IDs for the matching row. More than one ID can be
assigned. The original report needs matching ID parameters after the autocomplete fields. The ID fields will be
automatically hidden from the user.

We'll first define the report itself with two parameters. The inTitle-parameter will be the field we'll attach the
autocomplete field to and will be the one visible to user. The inFilmID-parameter will be the hidden parameter
that will hold the ID of the selected film when the user selects the autocomplete suggestion. The ID parameters
must follow the autocomplete filed in the parameter definition.

create procedure sp_DBR_FilmInfo( inFilmname varchar(30), inFilmID int )


begin

select 'dbr.pageview';

select f.title as 'Title',


f.description as 'Description',
f.release_year as 'Release year',
f.rating as 'Rating'
from mydb.film f
where f.film_id = inFilmID;

end

In the autocomplete procedure the ID values are placed starting from the third column. If no description is wanted
when using the ID values, use NULL-value in place of the second column.

create procedure sp_Autoc_DBR_Titles( inTitle varchar(255) )


begin

select Title, special_features, film_id


from mydb.film
where Title like concat( inTitle, '%');

end

Note 1: If the inFilmID-parameter is set as an optional parameter, the user is able to run the report even if
(s)he has not selected a row from autocomplete suggestion.

Note 2: If you use the automatic parameter inLogin in the autocomplete procedure to limit the options on a
per user basis, place the automatic parameter in the beginning at the parameter list.

38
Getting started

As a security precaution, please also note that when limiting the options using the inLogin-parameter, you
should check the validity of the ID inside the procedure as the user may change the browser DOM tree before
submitting the parameters.

Connected parameters
With connected parameters you can create dynamic select list/radio button parameters that depend on each
other. When the user selects an item on a select list/radio button, the subsequent select lists/radio buttons that
depend on the changed one will also change. Multiple select lists/radio buttons can be chained together to
create hierarchies.

Automatic parameters are also available in connected parameters.

The reference to another select list/radio button is made by using the same input parameter name in connected
report as in the main report.

• By using the same input variable name in connected report as in the main report. This method works when
the connected parameter query is defined as a stored procedure. This is usually the easiest method to use.
The method works only in cases where the same connected parameter appears only once in parameters.

• By using the relative address using keywords mydbr_param_prevX or mydbr_param_nextX , where prevX
refers to previous parameters and nextX refers to next parameters. For example mydbr_param_prev1 refers
to parameter 2 if attached to connected parameter 3. mydbr_param_prev2 would refer to parameter 1 in the
same case. This method can be used when the same connected parameter query is used more than once
in the report. The keyword is used in defined parameter queries and can be used in either direct SQL or as
a parameter for a stored procedure.

• By using the fixed address using keyword mydbr_paramX , where prevX refers to previous parameters and
nextX refers to next parameters, where the X refers to the order number of the parameter The keyword is used
in defined parameter queries and can be used in either direct SQL or as a parameter for a stored procedure.

As an example we'll create a report which has three level select list as a parameter. First the user selects a car
manufacturer, then the car model and finally a variant of the model.

First we'll create the report with required parameters

create procedure sp_DBR_car(


inManufacturer int,
inModel int,
inVariant int
)
begin
....
end

Then we'll define the required parameter queries. The first one is normal direct SQL query called
'car_manufacturers', which will be defined as a select list and attached to first 'inManufacturer' parameter.

select id, name


from car_manufacturers

The parameter procedure for the car models is defined using a name reference, where the parameter
inManufacturer refers to the parameter with same name in the report's procedure (sp_DBR_car). The
parameter procedure is named with the prefix sp_ADBR so we do not mix up it with reports with an sp_DBR
prefix.

39
Getting started

create procedure sp_ADBR_car_models(


inManufacturer int
)
begin

select id, name


from car_models
where manufacturer_id = inManufacturer;

end

The third parameter procedure, for car variant, depends both on first and second parameter and uses those
parameter names respectively:

create procedure sp_ADBR_car_variants_name(


inManufacturer int,
inModel int
)
begin

select id, name


from car_variants
where manufacturer_id = inManufacturer and model_id= inModel;

end

The connected parameter definition in Admin Tools / Parameter queries contains the procedure name or the
direct SQL query.

When parameter queries are attached to the report parameters, the connected parameters are available.

40
Getting started

The connected parameter returned can be automatically selected by returning value of 'selected' in the fourth
column (1st being the id, 2nd being the visible value for the user and 3rd being the optional optgroup in select/
checkbox (null if none)).

Automatic parameters
myDBR offers automatic parameters that can be used in reports, defaults and parameters queries.

• inLogin - username

• inIPAddress - Users IP address as reported by user's browser

• inLocale - Users locale when report is run (en_US, de_DE etc.)

• inUseragent - Browsers user agent

• inExportFormat - URL's export parameter value

• inAutoexecute - Makes myDBR accept default parameters and not wait for user confirmation.

• inHTTP_ACCEPT_LANGUAGE - User's default browser language

• inHTTP_REFERER - HTTP_REFERER, IP address of linked web page

• inAutoReportURL - Report's execution URL

• inAutoTheme - User's theme

• inImportFilename - Filename chosen in dbr.import

• inSessionIDHash - Hash value from user's Session ID

• additional user defined SSO automatic parameters - See Single Sign-On for additional automatic parameters

Example: Identifying the user running the report


myDBR keeps track of which username/password each connection was made with to the database. If you need
to know who the user is executing the report, you can add special parameter "inLogin varchar(30)" to
the report. myDBR will automatically set it to contain the user's username.

Variable name (inLogin) is defined in defaults.php if you wish to change it.

Following report outputs user's login name. No parameters are requested when the user runs the report.

create procedure sp_DBR_WhoAmI( inLogin varchar(30) )


begin

select 'User running the report is: ', inLogin;

41
Getting started

end

You can also use the inLogin parameter in parameter queries. If using procedures, the inLogin parameter needs
to be first parameter for the procedure.

create procedure sp_Autoc_DBR_Titles( inLogin varchar(30), inTitle varchar(255) )


begin

select Title
from mydb.film
where Title like concat( inTitle, '%') and owner=inLogin;

end

When using direct SQL in parameter queries, is is recommended to use parameter queries from stored
procedures. This allows myDBR to parse the automatic parameters safely.

create procedure sp_par_my_films (


inLogin varchar(30)
)
begin

select film_id, Title from mydb.film where owner=inLogin;

end

Parameters in linked reports


When linking reports together, the user has a report (s)he has run. The calling report itself may have parameters
that can be passed to the called report. Also, the context data from which the user clicks the linked report (a
row from a result set or a chart part) can be passed onto the report.

Following is a simple example of parameter passing in linked reports. In the example we have a report which
list films rented in given timeframe. From the list the user can click more details on the persons that have rented
the movie passing along also the customer ID. So, from the first report we'll pass on the reports own parameters
and also the data from the user selection.

The report to be linked into has three parameters: dates (start and end date) and the customer ID:

create procedure sp_DBR_CustomerRentals( inCustomerID int, inStartDate date, inEndDate


date )
begin

select f.title as 'Film',


r.rental_date as 'Rental time',
f.rental_rate as 'Rental rate'
from mydb.rental r
join mydb.inventory i on r.inventory_id = i.inventory_id
join mydb.film f on i.film_id = f.film_id
where r.rental_date between inStartDate and inEndDate and r.customer_id=inCustomerID;

end

The report from which the linking is done defines the linked report with the dbr.report. The parameters
referring to the report's result set are referred using column references. The reference to report's own parameters
is done using the variable name in parentheses.

42
Getting started

create procedure sp_DBR_RentalCustomers( inStartDate date, inEndDate date )


begin

select 'dbr.report', 'sp_DBR_CustomerRentals', 'inCustomerID=cid',


'inStartDate=(inStartDate)', 'inEndDate=(inEndDate)';

select concat(c.first_name, ' ', c.last_name) as 'Customer',


count(*) as 'Rentals',
c.customer_id as 'Customer ID[cid]'
from mydb.customer c
join mydb.rental r on r.customer_id=c.customer_id
where r.rental_date between inStartDate and inEndDate
group by c.customer_id, Customer;

end

In the example the inCustomerID=cid means that sp_DBR_CustomerRentals-procedure's parameter


inCustomerID will be filled with the result set data referenced with the cid column reference.
The inStartDate=(inStartDate) means that sp_DBR_CustomerRentals-procedure's parameter
inStartDate will be filled with the value of the inStartDate-parameter from sp_DBR_RentalCustomers
parameter.

Now when we run the initial report and click for more info on the customer, the linked report is run without any
questions on parameters since all the parameters have been filled with data from the initial report.

For more information on the linked reports see section Report Linking.

Report linking
One of the powerful features of myDBR is the ability to link reports together. A linked report is just another
report in myDBR structure with it's own parameters and permissions. Parameters can be taken from an original
report's own parameters and/or the report's data. A linked report may also have parameters that are requested
from the user at runtime.

Linking to column values


We have a film list out of which we want to pick one film and get more details out of it.

The film list is shown with a simple report:

create procedure sp_DBR_report()


begin

select Title, fid


from mydb.film_list;

end

43
Getting started

We want the user to be able to select a row from the list and pass the film id as a parameter to a linked report.
The report (sp_DBR_film) showing the details and the one we wish to link the existing report to has a parameter
'inFilmID' which is the film's ID.

create procedure sp_DBR_film ( inFilmID int )


begin

select description, release_year


from mydb.film
where film_id = inFilmID;

end

We can link the sp_DBR_film-report to the existing report with the dbr.report-command and give the parameter
inFilmID a value which will be taken from the user's selected row's second column. The resulting code can then
be added to the original report:

create procedure sp_DBR_report()


begin

select 'dbr.report', 'sp_DBR_film','inFilmID=film_id';

select Title, film_id


from mydb.film_list;

end

The parameter 'inFilmID=film_id' tells myDBR that to get the film_id-value from the row the user has selected
and pass it onto the sp_DBR_film-report's inFilmID parameter. The linked report can be assigned to any column
by passing the column reference to the dbr.report-command. If no reference is given, as in the example, an
extra menu icon is placed as a last column.

When the original report is executed, the user will see a mark indicating a linked report

and when opened, presents a list of linked reports. The name shown in the list is the name given to the report
when it was added to myDBR. The linked report needs to be added to myDBR in order it to show in the linked
report list.

The list of linked reports shown in the pull-down menu depends on user's permissions. The list shows only those
reports the user has access to.

44
Getting started

Linking to parameters
Sometimes the original report's parameters need to be forwarded to a linked report. For example if we have
a report that takes dates as parameters and produces rows based on the dates and the user wants to have
additional information (using a linked report) from the rows, the dates need to be passed along with the linked
report. To reference to the parameters, the parameter names can be put in parenthesis.

create procedure sp_DBR_report_dates(


inStart date,
inEnd date
)
begin
select 'dbr.report', 'sp_DBR_film_locations', 'inFilmID=film_id', 'inStart=(inStart)',
'inEnd=(inEnd)';

select f.film_id, f.description, count(*)


from mydb.films_shown s
join mydb.film f on f.film_id=s.film_id
where s.shown_date between inStart and inEnd
group by f.film_id, f.description;

end

The 'inStart=(inStart)' parameter tells myDBR to take the value of inStart-parameter from the original report
(sp_DBR_report_dates) and pass it to the sp_DBR_film_locations-report's inStart-value.

Passing on multiple parameters


Linked reports can have multiple parameters and also values from an original report's own parameters. In many
cases when doing drill-down reports, some parameters need to be carried over to the next report. The following
example illustrates this situation:

The original report has a couple of parameters itself:

create procedure sp_DBR_rentals ( inStartDate date, inEndDate date)


begin

select s.first_name, s.last_name, count(*), s.staff_id


from mydb.rental r
join mydb.staff s on s.staff_id=r.staff_id
where r.rental_date between inStartDate and inEndDate
group by s.first_name, s.last_name, s.staff_id;

end

The linked report has also parameters:

create procedure sp_DBR_rentaldetail (


inStaff_id int,
inStartDate date,
inEndDate date
)
begin

select r.customer_id, r.inventory_id, r.rental_date


from mydb.rental r
where r.rental_date between inStartDate and inEndDate and r.staff_id = inStaff_id;

45
Getting started

end

In order to link the report sp_DBR_rentaldetail to be called from sp_DBR_rentals we need to add that link and
define the parameters:

create procedure sp_DBR_rentals ( inStartDate date, inEndDate date)


begin
select 'dbr.report', 'sp_DBR_rentaldetail','inStaff_id=staff_id',
'inStartDate=(inStartDate)', 'inEndDate=(inEndDate)';

select s.first_name, s.last_name, count(*), s.staff_id


from mydb.rental r
join mydb.staff s on s.staff_id=r.staff_id
where r.rental_date between inStartDate and inEndDate
group by s.first_name, s.last_name, s.staff_id;

end

Letting the user edit the passed parameters


If you use format 'inStartDate<=-1' (instead of standard format 'inStartDate=-1'), the parameter becomes editable
by the user. See Creating editable reports.

Specifying the link location


If no link location (parameter in the dbr.report-command) is specified, the linked report will be attached to linked
report

mark.

You can also specify the link location to be a specific column, For example if user clicks ProductID, (s)he will get
more information about the product. Clicking on delivery date could show more information about the delivery
status.

The link location is specified in the dbr.report command. For example, you can attach the link to 'Name'-column:

create procedure sp_DBR_rentals ( inStartDate date, inEndDate date)


begin
select 'dbr.report', 'sp_DBR_rentaldetail', 'Name', 'inStaff_id=staff_id',
'inStartDate=(inStartDate)', 'inEndDate=(inEndDate)';

select concat(s.first_name,' ', s.last_name) as 'Name', count(*), s.staff_id


from mydb.rental r
join mydb.staff s on s.staff_id=r.staff_id
where r.rental_date between inStartDate and inEndDate
group by s.first_name, s.last_name, s.staff_id;

end

Output destination of the linked report


By default, the output destination of the the linked report is a new report page. The output destination can also
be a separate element in the original report, a popup or an inline element. Which one to choose, depends on
the report itsef. As a rule of thumb, you should select an output destination which is easiest to the user so
that user does not the lose context when clicking on more info. For example, if you have a report or rows user
goes through, and user can get more information about a row. You could then show the extra information in
a popup window or as an inline element allowing user to keep the context and still get more information. See
more options from Output destination of the linked report

46
Getting started

Referencing columns and parameters or passing on constants


Many of the myDBR commands can get parameters or reference columns of the next result set or refer to the
report's own parameters. You can reference to these by number or by name. Referencing columns/parameters
by name makes the code more readable and easier to maintain.

Column reference
Let's take example of dbr.sum-command which will create a summary row for given column(s). Teh command
takes one or more column references as parameters. These column references refer to columns of the next
result set. There are three different syntaxes for how one can reference the column:

1. Referencing by tag (recommended)

2. Referencing by column name

3. Referencing by column number

Referencing columns by tag


Tags are texts you add enclosed in brackets both in column reference and at the end of a column name. myDBR
automatically strips the tags from column names when creating the result. This is the recommended way of
referencing columns. You can either use the brackets or leave them off when making a reference. Brackets are
only required in dbr.summary.calc and dbr.calc calculation and in the dbr.report's column parameter.

select 'dbr.sum', 'length' ,'weigth';


select 'dbr.report', 'sp_DBR_show_product_detail', '[product]', 'popup',
'inProduct_id=product_id';
select 'dbr.calc', 'volume', '[length]*[weigth]*[height];

select product_id,
product as 'Product[product]',
length as 'Length[length]',
weight as 'Weight[weigth]',
height as 'Height[height]',,
null as 'volume'
from mydb.products;

Referencing columns by column name


The column name reference uses the column names. No extra code needed, but may need changes if creating
multilingual reports or if more than one column shares the same name.

select 'dbr.sum', 'Length' ,'Weight';

select product as 'Product',


length as 'Length',
weight as 'Weight'
from mydb.products;

Referencing columns by column number


The column number reference uses the column order number to reference the column. This is best suited
for small queries which you do not change that often. When complex queries change, this usually leads to
renumbering adding extra work.

select 'dbr.sum', 2,3;

select product as 'Product',

47
Getting started

length as 'Length',
weight as 'Weight'
from mydb.products;

Parameter reference
Some commands (dbr.report, dbr.url and dbr.editable) allow using the report parameters as values to be passed
on as a command parameter. There are two different syntaxes for referencing the column:

1. Referencing by parameter name (recommended)

2. Referencing by parameter position

Referencing parameters by name


When referencing parameters by name the parameter name is put in parenthesis.

create procedure sp_DBR_myreport(


inCategory int
)
begin
select 'dbr.url', 'http://myserver.com/myservice', '', 1, 'c=(inCategory)',
'p=product_id';

select name, product_id


from mydb.products
where category=inCategory;

When a report is called with inCategory=2 and the user selects a product row with id=200 the resulting URL will
be "http://myserver.com/myservice?c=2&p=200"

Referencing parameters by parameter position


When referencing parameters by parameter position the position is a negative number which refers to the original
report's parameter (e.g value -2 refers to 2nd parameter in original report). This is a compatibility option.

create procedure sp_DBR_myreport(


inCategory int
)
begin
select 'dbr.url', 'http://myserver.com/myservice', '', 1, 'c=-1', 'p=product_id';

select name, product_id


from mydb.products
where category=inCategory;

When report is called with inCategory=2 and user selects a product row with id=200 the resulting url will be
"http://myserver.com/myservice?c=2&p=200"

Passing on constants
One can also pass constants to linked reports / URLs by enclosing the constant value into quotation marks.
The value enclosed needs to be in formatting numbers with decimal point (12.12) and dates with format YYYY-
MM-DD.

In the example the inExtra-parameter gets a constant value "extra".

create procedure sp_DBR_myreport(

48
Getting started

inCategory int
)
begin
select 'dbr.report', 'sp_DBR_show_product_detail', '[product]', 'popup',
'inProduct_id=product_id', 'inExtra="extra"';

select product_id,
product as 'Product[product]',
length as 'Length[length]',
weight as 'Weight[weigth]',
height as 'Height[height]',
null as 'volume'
from mydb.products;

When report is called with inCategory=2 and user selects a product row with id=200 the resulting URL will be
"http://myserver.com/myservice?c=2&p=200"

Referencing crosstab total columns


Cross tabluation total columns are dynamically created to hold values for horizontal sum/min/max. One can
reference these columns by adding ".h" to the column reference. This allows report links to be placed into
summary columns and it also allows to use the summary values as parameters.

In the example the inExtra-parameter gets a constant value "extra".

create procedure sp_DBR_myreport()


begin
select 'dbr.report', 'sp_DBR_show_items', '[Items.h]', 'in_items_total=Items.h';

select 'dbr.crosstab', 'Quarter';


select 'dbr.hsum', 'Items';

select Name, Quarter, Items as '[Items]'


from mydata;

The second parameter for dbr.report ([Items.h]), places the report link to totals column for Items and
sp_DBR_show_items's in_items_total will get the value for horizontal summary for the Items column.

Report layout
myDBR handles the layout of the report automatically and by default centers the elements in a report. When
a report contains multiple elements, each element is treated as a separate element and is centered below the
previous one.

49
Getting started

Elements can easily be placed side by side using dbr.keepwithnext-command. An optional parameter defines
the space around the elements.

Perhaps the most common layout request is to place elements side-by-side into the report. This can easily be
done by using the 'dbr.keepwithnext'-command. In the following examples we have four result sets that
we want position into the report.

create procedure sp_DBR_Layout()


begin

select 'First result set' as 'First';

select 'Second result set' as 'Second';

select 'Third result set' as 'Third';

select 'Fourth result set' as 'Fourth';

end

Placing elements side-by-side using 'dbr.keepwithnext'-command


The 'dbr.keepwithnext'-command is placed before first element in the row.

create procedure sp_DBR_Layout()


begin
select 'dbr.keepwithnext';
select 'First result set' as 'First';
select 'Second result set' as 'Second';

select 'dbr.keepwithnext';
select 'Third result set' as 'Third';
select 'Fourth result set' as 'Fourth';

end

50
Getting started

The report will produce result like this:

Using templates
When you want full control of how the data is laid out, use templates using the dbr.template-command. A
template is a HTML/CSS/JavaScript code block where you can have placeholders for the data. By using the
templates you can also separate the layout code from the data logic making the report maintenance much easier.

Placing elements with the dbr.html-command


if you want just some HTML inserted into your report, you can for example place an HTML table around the result
set using the dbr.html-command. Here we have result sets side-by-side in the report, but with a wider margin:

create procedure sp_DBR_Layout()


begin
select 'dbr.html', '<table class="center"><tr valign=top><td>';
select 'First result set' as 'First';

select 'dbr.html', '</td><td width="50px"></td><td>';


select 'Second result set' as 'Second';

select 'dbr.html', '</td></tr><tr><td>';


select 'Third result set' as 'Third';

select 'dbr.html', '</td><td width="50px"></td><td>';


select 'Fourth result set' as 'Fourth';

select 'dbr.html', '</td></tr></table>';


end

Let's examine the added rows:

select 'dbr.html', '<table class="center"><tr valign=top><td>';

This will start the HTML table with class "center" (see userstyle.css for more info) and valign=top to put both
result set on the same level. The <td> at the end will prepare the first result set.

select 'dbr.html', '</td><td width="50px"></td><td>';

This will add a 50 pixel width space between the result sets. At the end we'll just close the HTML table definition:

51
Getting started

select 'dbr.html', '</td></tr></table>';

The report will produce a result like this:

Creating editable reports

myDRR allows for you to edit your data directly in myDBR. myDBR offers different kind of data editing:

• Inserting new rows to the database

• Editing full database entities where multiple fields are edited in one commit. This method is best suited for
use cases where you need update more than one column at once.

• In-place editing where you have a single value that is changed (multiple fields can be edited). This method
is best suited for use cases where the user updates existing data.

• Deleting rows from the database

The editing is done by linking another report (an editing report) to the original report to which myDBR passes
the editable data. Access rights to the editable report define who of the users sees the report as editable and
who as a normal non-editable report. If a user has access rights to the editable report, the fields are editable,
otherwise not.

Sample editing functionality


An usual use case is that user is shown a list of data and user is offered an option to add new row to the list.
Additionally user is able to edit the data in the list, either directly or row by row. This is an example of this.

52
Getting started

What we will do is following:

• Allow creating new rows

• Allow editing Description (text) directly in the list

• Allow editing Category (parameter from another table) directly in the list using a selectlist

• Allow editing a row at the same time using a linked report attached to 'Edit'-column

• Allow deleting a row using a linked report attached to 'Del'-column

The list is generated using a query:

select 'dbr.hidecolumns', 'film_id';

select
f.title as 'Title',
f.description as 'Description',
f.release_year as 'Year',
c.name as 'Category',
d.Name as 'Director',
'Edit',
'Del',
f.film_id,
f.category_id,
f.director_id
from mydata.film f
join mydata.category c on c.category_id = f.category_id
join mydata.directors d on f.director_id = d.director_id
order by f.film_id;

Creating new database entities (row)

We'll add a button in bottom of the list which will bring up a dialog with all the required data fields. The linked
report will be attached using dbr.report and it will insert the user data into the table and return a refresh command
to refresh the original list.

select 'dbr.button', 'New film';


select 'dbr.report', 'sp_DBR_Film_new', 'newfilm[]';

select 'dummy result set for the button';

Where:

• dbr.button will style the report link to be a button

• Report sp_DBR_Film_new will be used as action

• newfilm[] will place the output of the sp_DBR_Film_new into a dynamic DIV ([]) called newfilm. Reports
parameters will be asked in a popup so that user stays on same page.

Report code for the sp_DBR_Film_new:

CREATE PROCEDURE sp_DBR_Film_new(


inTitle varchar(69),

53
Getting started

inDescription text,
inRelease_year int,
inCategory tinyint,
inDirector_name varchar(80),
inDirector int
)
begin

insert into mydata.film ( title, description, release_year, category_id, director_id )


values (inTitle, inDescription, inRelease_year, inCategory, inDirector );

select 'dbr.refresh';

end

As the sp_DBR_Film_new is just a normal report we can attach functionality to the parameters: popup for the
category and make the director name an autocomplete field.

The dbr.refresh command at the end of the embedded linked report is returned to the original report causing
the refresh and showing the new item.

Editing a row, all columns at once


Editing a row works similarily to new row creation. Only difference being that we will pass the ID for the edited
row to the linked report and instead of doing an insert, we will do an update.

First we will attach the edit report to the 'Edit' column by adding the dbr.report-command before the select-
clause which shows the data to the user.

select 'dbr.report', 'sp_DBR_Film_upd', '[Edit]', 'popup', 'inFilm_id=film_id',


'inTitle<=Title', 'inDescription<=Description', 'inRelease_year<=Year',
'inCategory_id<=category_id',
'inDirector<=Director', 'inDirector_id<=director_id';

select
f.title as 'Title',
f.description as 'Description',

54
Getting started

f.release_year as 'Year',
c.name as 'Category',
d.Name as 'Director',
'Edit',
'Del',
f.film_id,
f.category_id,
f.director_id
from mydata.film f
join mydata.category c on c.category_id = f.category_id
join mydata.directors d on f.director_id = d.director_id
order by f.film_id;

The linked report to be called is sp_DBR_Film_upd and it is attached to the 'Edit'-column. As we want the user
to stay in the same page, we will put the linked report in a popup window. The edited row's ID (film_id) is passed
in as a non-editable field ("=") whereas all other fields will be user editable ("<=") in the parameter popup.

When user clicks on the 'Edit' link, the values are passed into the popup and user can change them:

The code for the sp_DBR_Film_upd looks like this:

CREATE PROCEDURE sp_DBR_Film_upd(


inFilm_id int,
inTitle varchar(80),
inDescription text,
inRelease_year int,
inCategory_id int,
inDirector varchar(80),
inDirector_id int
)
BEGIN

update mydata.film
set title = inTitle, description = inDescription, release_year=inRelease_year,
category_id=inCategory_id, director_id=inDirector_id
where film_id = inFilm_id;

select 'dbr.refresh';

END

Having both director name and id as parameter is due to the fact that the dialog used autocomplete value to
fetch the id when user enters director's name.

55
Getting started

'Delete a row'-example, use Javascript to enhance editing


You can add additional logic to your editable report by utilizing the dbr.report's 'callbefore'-function. This will
allow for you to execute a JavaScript call before the linked report is called.

As an example we'll create a basic delete functionality where the user selects the row to be deleted and myDBR
will ask for confirmation about the delete, deletes the row from database and when finished removes the deleted
row from the report. All will be done using Ajax without the need to refresh the page.

We will create a report which will delete a given row from the database

CREATE PROCEDURE sp_DBR_film_delete( in_film_id int )


BEGIN

delete
from sakila.films
where film_id = in_film_id;

END;

We'll modify the original report to include the link to delete-report and embed a delete confirmation javascript-
function.

select 'dbr.javascript',
"
function confirmdel(obj)
{
return confirm('Delete film \\''+$(obj).parent().children().eq(0).text()+'\\'?');
}";

select 'dbr.report', 'sp_DBR_film_delete', '[Del]', 'scriptdiv[]', 'in_film_id=film_id',


'event=click', 'callbefore=confirmdel';

callbefore Defines the JavaScript function to be called before the linked report is
executed

confirmdel A JavaScript function that is called before the sp_DBR_film_delete-


report is called. If it returns false, the report will not be called.

$(obj).parent().children().eq(0).text()
A jQuery call that gets the film title. (parent() is the table row, children().eq(0)
is the first column, text() is the content of the column)

[Del] The report is attached to the 'Del' column.

scriptdiv[] When the sp_DBR_film_delete-report returns a value (in this case a


JavaScript code block), it will be put to this embedded object. Adding [] to the
end of the object name makes myDBR to create the object dynamically when
needed and there is no need to create the object by using dbr.embed_object.
As the JavaScript is not shown, the location of the embedded object is not
important.

event=click Optional additon, causes the whole 'Del' table cell to accept the click instead
of just the text.

Now when the user clicks the 'Delete' column, the 'confirmdel'-JavaScript function is called with reference to
selected cell. If the user accepts the delete, the linked report is called and the output of the linked report is
placed into dynamically created 'scriptdiv'-div.

As a result we'll get a confirmation dialog asking user permission to delete the row:

56
Getting started

We can further improve the delete-report, by making it delete the selected row from the report once it is deleted
from the database. We do this by embedding small JavaScript-script to the delete-report. The linked report's
JavaScript context will have a predefined javascript variable 'mydbr_selected_cell' which will contain the cell
the user clicked.

CREATE PROCEDURE sp_DBR_film_delete( in_film_id int )


BEGIN

delete
from sakila.films
where film_id = in_film_id;

select 'dbr.javascript', "$(mydbr_selected_cell).parent().remove();";

END;

$(mydbr_selected_cell) will make the table cell a jQuery object, the parent().remove(), will delete
it's parent row.

In-place editing

In-place editing allows you to mark selected data so it will be editable directly in the report. You can specify
which column(s) are editable and define the actual editing report for it.

57
Getting started

In the example, we'll define in-place editing to be available in the following cross-table report. We'll
use the dbr.editable command to mark column 4 (Budget) to be updatable with the procedure
sp_DBR_update_crosstable.

Parameters for the command in the example are:

• id
The column to be edited

• sp_DBR_update_crosstable
The myDBR report the edited value is passed to

• inCategory=cat
sp_DBR_update_crosstable's inCategory-parameter is passed the value for selected 'cat' column value
(Category)

• inWeek=Week
sp_DBR_update_crosstable's inWeek-parameter is passed the value for selected 'Week' column value
(payment_week)

You do not need to pass the edited column value as it is automatically added as a last parameter to editing
report procedure

CREATE PROCEDURE sp_DBR_InPlaceEditing


BEGIN

select 'dbr.editable', 'id', 'sp_DBR_update_crosstable', 'inCategory=cat', 'inWeek=Week';

select 'dbr.crosstab', 'Week';


select 'dbr.count', 'cat';
select 'dbr.sum', 'Total';
select 'dbr.hsum', 'Total';

58
Getting started

select 'dbr.hidecolumns', 1;

select category as 'Film category[cat]',


payment_week 'Week',
amount as 'Total',
budget as 'Budget',
category_id as 'id'
from film_budget;

END

The report that is doing the actual updating can either reject the update and return the original value or simply
update the new value. The report gets all the parameters specified in dbr.editable-call and an additional
parameter for the value.

The last parameter for the editing procedure is automatically populated by the value of edited field. You can
name the parameter as you like (inValue in the example).

CREATE PROCEDURE sp_DBR_update_crosstable(


inCategory int,
inWeek int,
inValue float
)
BEGIN

/* Check the data */


if (inValue>0) then
/* Accept the update, no need to return a value */
update film_budget
set budget = inValue
where category_id=inCategory and payment_week=inWeek;
else
/* Reject the update, return the original value */
select budget
from film_budget
where category_id=inCategory and payment_week=inWeek;
end if;

END

59
Chapter 4. Preferences
Report categories
Report categories allow you to organize the reports into different categories inside the report folder. Each
category has a name (title), optional display order (number) and a color.

Report category names can be localized using the myDBR's #{}-notation. See more information at Localization

Users
myDBR users
When myDBR is selected as the authentication method, user logins and passwords are defined here.

• Login - the login name user uses when (s)he logs in

• User's name - Real life name for the user

• Password - Password used

• Is admin - Determines whether the user is allowed to maintain myDBR reports

Logins are stored into the table mydbr_userlogin. The password stored using the phpass-algorithm.

Importing users from another system


In order to import large numbers of users into the myDBR user repository, you can import them directly to
mydbr_userlogin-table. password can be either MD5-hash from the password or a password geterated by
PHPass. MD5-hashed passwords are automatically converted to salted ones once the password is changed.

60
Preferences

insert into mydbr_userlogin( user, password, name, admin )


values ('newuser', md5('password'), 'New User', 0 );

From myDBR 4.0 onwards passwords are stored as salted passwords using PHPass PHPass.

Groups
User group concept
With user groups, myDBR allows you to assign privileges to groups of users in addition to individual users.
This will make maintaining the report privileges easier (see Access rights). In 'User Groups' preference you can
maintain the user groups (add / delete / rename) and add users to specific groups.

Adding group
You can simply add a group by entering the group name and press 'Add group'-button. If you are planning on
linking users in a group dynamically (see 'Data-driven user classification' in Access Rights) choose the group
name accordingly.

Removing group
To remove a group, press the Remove group-button

next to the group name.

Adding a user to a group


Once a group is added you can add user to it. This can be done by pressing the Edit Group -button

next to the group name. This will open a search field where you can enter a username (or part of it). From the
resulting list you can check the users to be added and then press 'Add selected user(s) to group xxx'-button.
A user can belong to more than one group.

Remove a user from a group


To remove a user from a group, press the Remove user-button

next to the user's name.

Styles
Pre-defined styles can be used in the reports for columns and rows. Reports can share these definitions. Row
styles contain pure formatting directives. Column styles can also format the data inside a cell.

Each style has a name (used in reports to refer to the style) and the actual style definition.

See more information on styles at Commands->Styles.

Row styles
Report rows can contain multiple data types and therefore the row styles contain only the visual formatting of the
data. Row styles can be used in a report by including a hidden style column with the report data and identifying
the column to contain the style definition. Row styles are defined by simply providing CSS definition(s) separated
by a semicolon.

61
Preferences

A simple row style definition for changing the font color and weight would be:

Column styles
Column styles are used to format a specific column. The data may be formatted based on the value of the data,
since all the values in the column share the same datatype. The format of a column style is "positive style; zero
style; negative style". Each style element has a format of: "[css style] printf arguments". Each part of the style
can be omitted.

In order put negative numbers in red, a style is created with specific formatting.

Styles can be edited by pressing the

edit-button and deleted by pressing the

delete-button.

For more information on using the styles, see command Applying styles.

Parameter queries
See Getting started / User parameters for details.

Server side files


With 'Server side files' you can edit the files in mydbr/user directory. The most common use case is to edit
the userstyle.css-file which can be used to define the dbr.resultclass, dbr.rowclass, dbr.colclass,
dbr.tab.class or dbr.accordion.class definitions.

defaults.php
myDBR has many defaults and options defined in mydbr/defaults.php. The values in the file are defined as a
PHP array. You can override these values in mydbr/user/defaults.php. The mydbr/user/defaults.php-file will be

62
Preferences

kept intact between server updates. Do not make changes to mydbr/defaults.php as it is overwritten in updates.
The "Server side files / defaults.php" points to mydbr/user/defaults.php

Example defaults.php definitions:

$mydbr_defaults['page_title'] = 'myDBR Own';


$mydbr_defaults['export']['wkhtmltopdf']['command'] = '\"Program
Files"\wkhtmltopdf\wkhtmltopdf';

userstyle.css
Any CSS definition in myDBR can be overwritten in userstyle.css. Also, if you have common css-classes shared
between reports, this is the file to store them.

Templates
A template in myDBR is an HTML/CSS/JavaScript code block, which is used to format report content. A template
can contain any valid HTML, CSS, or JavaScript content. Templates allow fully free formatting of report content
and can be used to create both strict forms and any other user defined formatting.

The benefit of using template is that it allows separation of database queries from the presentation.

A template consists of a header, row and footer part. An optional header part is an HTML block which will be
output before any report content is displayed. The row part is repeated for each row in result set. The footer
part is displayed after the result set has been processed.

If your query returns only one row, a template can be defined fully in row-section. If your query returns multiple
rows, separate header and footer elements can be defined.

See Commands / Templates for more info how to use templates.

Notifications
Login notification allow admin to present a message to the users.

Login notification
Login notification is shown to the users above the login screen. You can include plain text or include HTML
code in the notification.

63
Preferences

Main-screen notification
Main-screen notification is shown to the users in the Notifications area in the Main screen.

Environmental settings
These settings define the generic settings for the myDBR installation. The installation defines an instance of
myDBR connected to a defined database.

Report Database Setup


These settings define the connection info for the myDBR installation and are stored in mydbr_config.php
on the server. In order to change these re-run the installation. Installation will check that the required objects
exist in the selected database.

Database type MySQL is accessed through mysqli, Sybase ASE and Sybase Anywhere are accessed
through FreeTDS and MS SQL Server can be accessed through FreeTDS or on Windows
server using Microsoft's sqlsrv-driver.

Host The computer where the reporting database is located. Hostname or an IP address.

Port If connection is using TCP/IP port, it is defined here.

Database Name of the database containing the mydbr objects.

User Admin user's username. This user must have privileges to the mydbr database object,
including the right to execute stored routines. In the example installation we created user
mydbr for this purpose.

Password Password for the admin user.

Authentication
Determines which authentication module is used.

myDBR user authentication User logins and passwords are defined inside myDBR. See Users.

Database login A user is authenticated through the database's own user / password
procedure. The user must have access to the database containing the
reported data.

Single Sign-On (SSO) The user is authenticated by an external web-site which then redirects the
user back to myDBR. See SSO for more information.

Active Directory The user is authenticated using Active directory.

Custom Custom authentication allows using external authentication, while still


keeping the simplicity of login process. See Custom authentication for more
information.

Session lifetime Session duration allowing user to stay connected even when browser is
closed. When returning to myDBR a previous session is restored. Please

64
Preferences

note that yoy may need to change PHP's gc_maxlifetime-directive in order


to have longer lifetime.

URL hash seed myDBR's report URL's will be protected by a hash value. By defining this
value, admin can change the seed of the hash making URL unique to server.
Changing this value will change the URL's to reports. If value is empty, a
predefined value is used.

Password settings when using myDBR authentication


Defines password rules.

Single Sign-On (SSO) settings


SSO secret token The token used to verify that SSO redirects are coming from the authenticated SSO
server. This token is known only to the myDBR server and SSO server

SSO Server URL The URL to which the user is redirected for login. myDBR will add a random token and
a return URL as parameters to this URL. See SSO for more information.

Active Directory settings


Domain Controller List of Domain Controllers. If you want to balance the queries over multiple
controllers, you can specify multiple controllers by separating them with comma.
Example dc01.mydomain.local

Account Suffix The full account suffix for your domain. Example mydomain.local

Base DN The base dn for your domain. This is generally the same as your account suffix,
but broken up and prefixed with DC=. Your base dn can be located in the extended
attributes in Active Directory Users and Computers MMC.

Username / Password An AD username with access rights to read the AD structure.

Password reset
Password reset allows user's to reset their own passsword via email request when using myDBR authentication.
User request a password reset request and receives via email a password reset link. The link is valid for the
defined period. In order to use this functionality, the mail settings need to be set and user's myDBR account
needs to have a valid email address. New reset link request reset the old ones. The link can be used only once.

Enabled Defines if the feature is enabled

Username / Email / Username Defines which information is asked from the user when (s)he requests a
or email password reset link

Admin user's password can be If this is set user can request a password reset link for admin user. if
changed unchecked, admin logins are protected from password change

Reset link valid for XX minutes User can use the link sent only for XX minutes. After that the link expires
and cannot be used.

Show reset link only after login If this is set, the link to password reset functionality is shown only after
failure unsuccessful login attempt. If option is not set, the link is always visible.

Customizing the password reset email


You can customize the password reset email templates defined in mydbr/interface/languages/templates-folder.
By creating a template with same name in mydbr/user/templates/-folder. A template can contain HTML code
and supports following predefined template variables:

• #{name} User name

65
Preferences

• #{hostname} The server URL

• #{reset_link} Password reset link

• #{link_valid_minutes} How many minutes the password reset link is active

• #{page_title} Page title defined in Environment settings

Automatic login
With automatic login enabled, no user login is required. All users accessing the reports will use the same
login info. This option is used in cases where myDBR is used as an public reporting source (intranets, public
extranets). Username and password here should in normal cases be set to non-admin username (not allowing
everyone to change the content). Admin access can be gained by pointing the browser to login.php instead
of the usual index.php.

Username The username to be used as a shared username

Password The password to be used as a shared password

Formatting defaults
These settings are shared between the users.

Date Default date format

Time Default time format

Thousand separator Default thousand separator

Decimal separator Default decimal separator

Sum prefix, Min prefix, Max Prefixes to be used in summary rows when aggregate functions are used
prefix, Average prefix, Count in reports
prefix

myDBR report prefix By default myDBR will search for unused reports based on this prefix. Any
stored procedure that starts with this prefix is offered to be added into the
myDBR reporting structure

Theme The UI style to be used in the application

Language Languages available under myDBR installation. This selection will allow
admin to translate the system to selected languages and users to set these
languages as default

Mail
Mail is used by dbr.mail extension and the password reset feature.

Host SMTP mail host name

Port TCP/IP port used by the SMTP mail server (25 is the default for non-encrypted mail)

Secure The mail can use TLS / SSL encryption

Username / Password Username / password for protected mail server access

From Name/Email Defaults to be used for "From:"

ReplyTo Name/Email Defaults to be used for "ReplyTo:". Optional. If not set no separate ReplyTo header
is used in mail.

66
Preferences

If separate "From Name/Email" and "ReplyTo Name/Email" is wanted for password resets, these can be set by
overriding the defaults.php's 'password_reset' values in user/defaults.php.

The password reset instructions are sent to user's mail address. The mail templates are stored in mydbr/
interface/languages/templates. If your language template is not there, you can create one by copying the existing
templates and modifying them. If you want to override the existing templates and create your own ones, you
can place one with same name into mydbr/user/templates.

OEM
OEM customization options are shown if you have an OEM license.

Licensee The OEM license holder. Shown in the About-dialog.

Application name When defined, replaces the 'myDBR'-text in upper left corner in non-report screens.

Disable header When selected, no header is shown. Suitable for installations where myDBR is used
just for the reports, navigation is done elsewhere.

Disable footer When selected, no footer is shown.

Footer When defined, replaces the standard footer text

About info Additional info to the About-dialog

Login image CSS An example of the CSS which defines the logo shown in the login screen

Installed modules
myDBR supports multiple charting modules. myDBR comes with Flash chart support preinstalled and can be
enhanced with Image chart support (PNG-charts) and with Graphviz-charts. In order to take advantage of image
charts and Graphviz-charts, you need to install the support for these. See Optional installations on how to install
these modules. wkhtmltopdf allows you to export myDBR reports at full quality.

Flash-charts (preinstalled) Default charting module

Image-charts ChartDirector image support. ChartDirector is an optional install to myDBR.


ChartDirector is a commercial application whose license is included with
myDBR.

Graphviz-charts Graphviz support is enabled in the environment.

wkhtmltopdf wkhtmltopdf support for better PDF output

Preferred chart Image- and Flash-charts can both draw similar charts. When both Flash-
chart and Image-chart support is enabled in the environment, this determines
the default charting module (you can still specify the module used case-by-
case in the report). myDBD automatically detects supported charting in the
client and uses theappropriate module.

Default chart format Choose between SVG and PNG charts. SVG charts are rendered in the client
and make full use of client browsers native font subsystem producing crisp
charts. PNG charts are images generated in the server.

Use embedded charts When checked, the chart data is embedded in the report.

Miscellaneous settings
PHP include path Enables you to specify the PHP include path in environments where some of the
modules are not in default path.

67
Preferences

Proxy server If your server is behind a proxy, the automatic update may not work until the proxy
server is defined. Format is host:port (no http:// prefix).

Single Sign-On (SSO)

Introduction
myDBR allows you to use an external server for user authentication. The server must implement the
Authentication protocol specified below but otherwise there are no restrictions on how the server is implemented.
The server and myDBR share a secret token which verifies that requests coming from the myDBR and the
server are valid. The secret token is defined in myDBR Environmental settings.

myDBR also offers SSO implementation for Google authentication.

Authentication protocol
In this setup SSO is selected as a authentication method in Environmental settings.

1. A user visits the myDBR site for the first time

2. A user is redirected to the SSO server URL (as specified in settings). In addition myDBR adds the following
three parameters to the URL:

• url The URL to which the user should be redirected once login has been completed

• token A random token which is used by the SSO server to calculate a verification hash

• hash A hash value calculated as sha1(url + token + secret) so you can verify the call comes from myDBR.
If the hash does not match, one can abort the process (other than myDBR made the call)

3. The SSO server performs authentication of the user, e.g. by showing a login screen or determining the user
information from an already logged in user

4. The SSO server redirects the user to the URL provided by myDBR. In addition the SSO server must add
the following parameters to the URL:

• user Login of the user

• name Full name of the user

• groups Optional list of groups user belongs to separated by '|'

• email Optional user's email address

• telephone Optional user's telephone number

• admin A flag 1 / 0 indicating if user is an admin or not

• extra1 Optional extra parameters (extra1, extra2, extra3...). Will be concatenated in hash calculation.
extras = extra1+extra2+extra3.

• hash A verification hash calculated as sha1( user + name + groups + email + telephone + admin + extras
+ token + secret )

5. myDBR verifies the hash received from the SSO server, and creates or updates the user information for the
specified users

6. The user is now logged in to myDBR

68
Preferences

Extra parameters

It is possible to pass on extra parameters in SSO authentication. These parameters will become myDBR's
automatic parameters. To add an extra parameter:

1. Add it to the SSO URL. The first extra parameter will be named as 'extra1'

2. Add it to the SSO URL hash between admin and token

3. Define the automatic parameter name that will be used in parameter:


$mydbr_defaults['automatic_parameters']['sso_extra1'] =
'in_SSO_OrganizationID';

if you have more than five extra parameters, increase the $mydbr_defaults['parameters']
['max_sso_extra_parameters'] in user/defaults.php

User's groups

The authentication protocol contains optional parameter groups which can be used to define SSO user's groups
separated by '|'. Parameter contains a list of groups user belongs to. When logging in myDBR will do following
things:

1. If a user's group does not exist in myDBR it will be added

2. The user will be added to groups defined by the groups-parameter

3. The user will be removed from any other group

4. If the groups-parameter is empty user is removed from all groups

Example SSO Server

An example standalone SSO Server has been included in the user/sso/sso_example.php.

Debugging the SSO protocol

If you have trouble implememnting the SSO protocol, you can enable the debug option which will show more
info when SSO authentication fails. To enable the debug add following to user/defaults.php:

$mydbr_defaults['single_sign_on']['debug_failed_login'] = true;

Local myDBR login when SSO is enabled


If SSO is set as a login method, you can still login with myDBR login by adding &local=true to login URL.
For example if you have installed myDBR at localhost/mydbr you would login locally using http://
localhost/mydbr/index.php?a=login&local=true

To prevent users logging in with the myDBR login when SSO is being used, remove unnecessary myDBR logins
and secure the admin password.

Logout process in SSO


When using SSO, both login and logout needs to be done simultaneously from both main application and
in myDBR. You can make myDBR log out and redirect user's browser to desired location by defining the
$mydbr_defaults['logout']['url'] variable in the user/defaults.php.

If you need to define the redirect destination dynamically, you can use the 'url'-parameter in myDBR's
logout-call (/mydbr/logout.php?url=https%3A%2F%2Fmyserver.com%2Fservice). In order to protect myDBR
from open redirect vulnerability, the possible values of the 'url'-parameter needs to be defined in the
$mydbr_defaults['logout']['allowed_redirect_urls_in_url_parameter'] array in the user/defaults.php.

69
Preferences

Third way of defining the redirect destination is to define a automatic parameter logout_url_redirect which
will be used when user logs out in case no url-parameter is passed to logout.php. This method can be used if
the redirect destination depends varies.

To override myDBR logout link text and location in autologin and SSO, change the $mydbr_defaults['logout']
parameters.

Example for integration with SugarCRM


The following example has been tested with SugarCRM CE 5.5 and makes the following assumptions:

• myDBR is installed in /var/www/htdocs/mydbr and accessible from your web-browser via http://
localhost/mydbr

• SugarCRM is installed in /var/www/htdocs/sugar and accessible from your web-browser via http://
localhost/sugar

Add the SSO code to SugarCRM

1. Create a new directory /var/www/htdocs/sugar/modules/mydbr

2. Create a new file in that directory and name it controller.php

3. Paste the following code to controller.php and save the file.

<?php
require_once('include/MVC/Controller/SugarController.php');

define( 'MYDBR_SECRET', 'secret-token-defined-in-mydbr-environmental-parameters');

class myDBRController extends SugarController


{

function action_login()
{
global $current_user;

$role = new ACLRole();


$roles = $role->getUserRoles( $current_user->id );

$separator = '';
$groups = '';
foreach( $roles as $role ) {
$groups .= $separator . $role;
$separator = '|';
}

$user = $current_user->user_name;
$name = $current_user->title;
$token = $_REQUEST['token'];
$url = $_REQUEST['mobile'];
$hash = $_REQUEST['hash'];
if ($hash!=sha1($url.$token.MYDBR_SECRET)) {
die();
}
$hash = sha1( $user . $name . $groups . $token . MYDBR_SECRET );

$url = $url . '?user=' . urlencode($user) . '&name=' . urlencode($name) .


'&hash=' . $hash .'&groups=' . urlencode($groups);

header('Location:' . $url);
die();

70
Preferences

}
}

Configure myDBR for SugarCRM SSO

1. Go to "Admin" -> "Environment Settings"

2. In "Authentication" select "Single Sign-On"

3. Add following line to mydbr/user/defaults.php:

$mydbr_defaults['single_sign_on']['url_parameter'] = 'mobile'; // For SugarCRM 6.x


which does not allow the default 'url' parameter

4. In "Single Sign-On settings" add the following information

• SSO secret token secret-please-change-me

• SSO Server URL http://localhost/sugar/index.php?module=mydbr&action=login

myDBR is now accessible with-in SugarCRM. If you are logged in to SugarCRM and visit http://localhost/
mydbr you will be automatically logged in to myDBR as well

Add myDBR site to SugarCRM (optional)

1. In SugarSRM go to "Admin"->"My Sites"

2. Click "Add Site"

3. Enter the following:

• Name ... myDBR

• Website ... http://localhost/mydbr

• Type ... Global

4. You can now access myDBR from the SugarCRM's "Others" tab

Google authentication
The SSO's Google authentication allows authentication using Google login. Assuming your myDBR install
location is https://yourserver/mydbr, to enable goole login do following:

1. Choose Google login in myDBR → Admin Tools → Environment settings → Single Sign-On settings

2. Create a Google API Console project and client ID https://developers.google.com/identity/sign-in/web/


devconsole-project

3. Copy the Client ID and Client secret to respective fields in myDBR → Admin Tools → Environment settings
→ Single Sign-On settings → Google
4. Define a "Authorized redirect URIs" which will be a URL to https://yourserver/mydbr/lib/sso/google/

5. In myDBR set the SSO Server URL to be: https://yourserver/mydbr/lib/sso/google/index.php

6. By including the hosted domain of the users, you restrict sign-in to accounts at that domain

7. Wait for a moment to let Google setup to be effective and login using Google login

71
Preferences

Active Directory

Introduction
myDBR allows you to use Microsoft Active Directory for user authentication. This includes user creation,
authentication, group creation and user group handling. The functionality is the same as in myDBR's SSO-
authentication.

Active Directory settings


In order to use Active Directory authentication, the following settings needs to be defined in Environment settings:

• Domain Controller Active Directory server(s) handling the security authentication requests. If you want to
balance the queries over multiple controllers separate them with commas.

• Account Suffix The full account suffix for your domain

• Base DN Where to start the searches in Active Directory. If left empty myDBR will attempt to detect this
information automatically from your domain controller

• Username Username which has read privileges to Active Directory

• Password Password for the Username

Active Directory configuration

To configure myDBR's Active Directory-authentication in the Active Directory server, the following groups need
to be defined:

• myDBR Groups A group defining the AD groups which will be considered as myDBR groups. The default
name for this group is 'myDBR Groups'. All other myDBR groups must be members of this group. If you
wish the change the default group name, place definition $mydbr_defaults['active_directory_mydbr_groups']
= 'NEWMYDBRGROUPNAME'; into mydbr/user/defaults.php.

• myDBR Admins If user belongs to this group (s)he is granted admin rights to myDBR. The default name
for this group is 'myDBR Admins' and the group must be member of 'myDBR Groups'. If you wish the
change the default group name, place definition $mydbr_defaults['active_directory_mydbr_admin_group'] =
'NEWADMINGROUPNAME'; into mydbr/user/defaults.php.

• Other groups inside 'myDBR Groups' to define user groups to which you can define reports to Any group
added to 'myDBR Groups' will be shown as a user group inside myDBR. This will allow one to define different
access rights to different reports. Users can be member of these groups directly or via other AD groups
belonging to these groups.

All of the predefined group names can be customized in mydbr/user/defaults.php.

myDBR determines if user in Active Directory is a myDBR user by checking if the user belongs to any of the
groups listed in Active Directory group 'myDBR Groups' or is directly member of 'myDBR Groups'.

User's groups

All user group handling is done inside Active Directory. When a user logs in her/his groups are checked against
the Active Directory provided group list.

1. If a user's group does not exist in myDBR it will be added

2. User will be added to myDBR groups defined in Active Directory

3. User will be removed from any other group

72
Preferences

Local myDBR login when AD login is enabled


If the Active Directory is set as a login method, administrators can still login with myDBR login by adding
&local=true to login URL. For example if you have installed myDBR at localhost/mydbr you would login
locally using http://localhost/mydbr/index.php?a=login&local=true

To prevent users logging in with the myDBR login when AD is used, remove unnecessary myDBR logins and
secure the admin password.

Custom authentication

Introduction
Custom authentication method allows one to write own authentication method by extending the
Custom_authentication-class found in mydbr/user/custom_authentication.php.

Usage
When user enters username and password to login dialog, the values are passed into static function
Custom_authentication::authenticate($username, $password). If user is successfully authenticated with custom
code, the function should return a user record. If authentication is not successfull, a null is returned.

User record is an array with obligatory fields: name, admin and groups. Additionally, the user record can have
email and telephone info for the user.

$user['name']: username
$user['admin']: 1=admin, 0=normal user
$user['groups']: array of groupnames user belongs to. Example: array('Sales', 'HR',
'Production'), null if groups are not handled here but inside myDBR
$user['email']: optional user's email
$user['telephone']: optional user's telephone number

Remote servers

With remote servers you combine information from multiple databases into the same report. This is done by
connecting two or more installations of myDBR to share the information.

73
Preferences

See Remote calls to other myDBR servers for more info.

Demo / Localization
Demo
Here you can install / remove the demo reports. Demo reports are installed into a separate folder and will not
interfere with your own reports.

Localization
The localization option allows for you to localize myDBR to your own language. myDBR will by default offer
both application (user interface elements like texts, buttons, menus etc.) and reports based on user's locale
(browser setting), if localization for that language exists. You can create multilingual reports which offers texts /
formatting for the user's locale.

To localize myDBR do following:

1. Create a locale file into mydbr/interface/languages. You can take en_US.php as basis. You can see available
locales from myDBR (select * from mydbr_languages)

2. Translate the texts in the locale file. If you do not translate all the texts, remove the non-translated items.
myDBR will use default language texts for the non-translated texts

3. Make sure your localization file has same permissions as the ones supplied by myDBR

4. Include the language into the active languages from under Environment settings/Formatting defaults/
Language

5. Check that your added language has defined formatting options in the mydbr_languages-table

If you create a localization file, please consider sharing it with others by sending it to myDBR.com. It will then
be added as part of the official build.

About
Shows the version information and allows for you to update the application. The update process is fully
automatic.

74
Chapter 5. Managing reports
General

Adding/deleting folders

Folder structure

The folder structure is the way reports are presented to the user. Plan the folder structure in a way that the logic
is easy for the end user. With folders you can classify reports into different categories.

Folder permissions

Folder permissions determine which users / user groups can see and open the folder.

In order not to clutter user's view with the Admin reports (statistics, maintenance etc.) these reports can be
placed in a folder accessible only by the admin.

Linked reports often contain parameters that are derived from the data of the report they are connected to.
These reports are not intended to be used directly (lack of control on the input parameters). By placing the linked
reports to hidden folders, this can be avoided.

Adding/deleting reports

When attaching a new report to the report structure, myDBR searches for the stored procedures that have the
myDBR report prefix (as set in Environmental settings) and have not yet been attached to the structure and lets
you choose the one to be added. You can invoke the SQL Editor and create a new report procedure.

Once the report is added to the myDBR, the report parameters and report privileges can be added.

75
Managing reports

Moving reports and folders

To move a report or folder, select 'Move report' in the edit view and then navigate to the folder where you want
to move the report or folder. Finally select 'Move folder/report here' to complete the move. The access privileges
and parameter settings for the report will remain intact.

Defining report parameters

The 'Report parameters'-section defines how report's parameters are presented to the user. The actions:

• Parameter - the parameter's name in the database.

• User input - determines how the parameter is presented to the user (a field, a popup, a radio button or an
autocomplete field).

• Default value - determines the parameter's value at first run. Subsequent runs remember the parameters used.

• Parameter name for user - instead of using the parameter name from the database, define a new one

See User Parameters for more information.

Report privileges

In 'Report privileges' the report access rights are determined. Users can have access to the report by explicit
access right or through a access right given to a group user belongs to.

Report access rights


myDBR maintains the report access rights based on the assigned rights. An access right for the report can be
set to an individual user, to all or to a group maintained inside myDBR. Also, a report can be set accessible
as without the need to login.

Access rights are determined under a report's 'edit' link.

All logged in users

Every user who is logged in can run the report.

Access without login allowed via direct URL

Anyone how knows the report's direct URL can view the report. Login is not required. For more details see
direct URL

Individual users

Individual users are the users in the particular database.

Groups inside myDBR

In myDBR preferences one can maintain a set of groups and assign Individual users to the group. These groups
are static groups in terms of users who belong to the group.

Identifying the user running the report

myDBR keeps track with which username/password each connection was made to the database. If you need
to know who is the user executing the report, you can add special parameter "inLogin varchar(30)" to
the report and myDBR will fill it automatically to contain users username.

76
Managing reports

Variable name (inLogin) is defined in defaults.php if you wish to change it.

Following report outputs user's login name. No parameters is asked when user runs the report.

create procedure sp_DBR_WhoAmI( inLogin varchar(30) )


begin

select 'User running the report is: ', inLogin;

end

Showing report privileges at one glance

Adding &priv=1 to the url in main view lists the report privileges at one glance.

https://localhost/mydbr/index.php?m=1&priv=1

Direct URL access to reports


myDBR allows you to run reports directly by providing the required information in the request URL. Direct URLs
are useful in the following cases:

• Users can bookmark their favorite reports in the browser and run the report without having to select the report
from the list first.

• Web site developers can embed reports in existing web-pages, allowing seamless integration of myDBR to
any web site

• Reports can be published to be used without the need to log in to myDBR. These reports are accessible to
anyone.

• Combined with the export capability and with http basic access authentication data can be easily exported
from myDBR reports.

• Getting report images from myDBR to be used inside IMG-tag in external application

URL parameters
myDBR passes all parameters required to run the report in the URL. The parameters in the report are the stored
report's parameters. If not all the required parameters are provided, the missing parameters are requested from
the user.

The report parameters passed in the URL are labeled with a sequence number (1=first parameter, 2=second...).
Those parameters that are requested from the user, and that the user can change are marked with 'u'.
Parameters derived from the database are considered as protected parameters and are not user changeable.

The advantage of the user changeable / protected parameters is that it eases up the report authoring process.
When you know that a user is passing on a protected parameter, you can trust that user can use that parameter
in the query.

The direct URL has the following parameters which can be added and changed by the user:

• u1,u2,u3,... Report parameters. The number behind the 'u' refers to the order number of the parameter is
the report's stored procedure (u2 = stored procedure's user changeable second parameter)

77
Managing reports

• e1,e2,e3,... Report parameters that user can change before the report is run. The number behind the 'e'
is the same as in 'u'

• hdr=0 Removes myDBR header and footer from the output. This can be used for embedding the report or
creating a printable report.

• getchart=1 Makes image report to return just the image data. Allows usage in IMG-tag.

• embed=X When used, the code generated includes only the generated objects code (embed=1), No <head>-
tags are generated. This is used when myDBR's output is used inside another web page. The ID passed on
is to generate a unique ID for the object. embed=2 is meant for embedding myDBR reports to Dashboard.

• embed_image Override default setting and use embedded images in the chart.

• image_format Override default image format setting

• export=export_type See Export

• lang=language_code Can be used to override user's language setting. Language code (fi_FI, sv_SE, en_US
etc) determines the myDBR user interface and used formatting on dates, decimal numbers etc.

The following standard parameters cannot be modified by the user:

• p1,p2,p3,... Fixed report parameters not shown to user if more parameters are asked. The number behind
the 'p' refers to the order number of the parameter is the report's stored procedure (p2 = stored procedure's
fixed second parameter).

• s1,s2,s3,... Fixed report parameters which will be shown to user if more parameters are asked. Otherwise
behaves the same as 'p'-parameters.

• h Security hash, calculated by myDBR. This parameter ensures that the URL is valid, comes from the trusted
source.

• r report ID / report procedure name

• sr md5(report procedure name), can be used as alternative to r-parameter

• m m=folder id for the report

Generating a direct URL


You can generate a direct access URL by accessing the report inside myDBR and copying the URL. If you
add '&hdr=0' to the URL, the headers and footers will be omitted. Please note that 'u' parameters are user
changeable. See 'URL parameters' below.

To calculate the URL hash by yourself you need to know the URL hash seed value used in the installation. To
calculate the hash do following:

78
Managing reports

Concatenate:

• reportID (either the numeric ID or the stored procedure name if you wish to make a portable URL )

• as an alternative to the reportID you can use sp-parameter which contains md5-value from the stored
procedure name

• For each 'p' parameter: concatenate 'p' + parameter number + the urlencoded parameter value

• Optional report location parameter 'm' with value

• The seed in the Environment settings

Hash is a SHA1 value from this.

Example
We have a report 'sp_DBR_myreport' with ID 20 (r=20) and URL hash seed 'secret'. The report resides in folder
7 (the m-parameter in URL this parameter is optional). The report definition looks like this:

create procedure sp_DBR_myreport (inAccountID int, inNotice varchar(30), inDate date )


begin
...
end

Now we'd like to create a direct URL in which the user could change the date but not be able to change the first
two parameters. We name the first two parameters with 'p' and include those in the hash calculation. Parameter
list with example data looks like this:

• p1 = number 200

• p2 = text 'My param'

• u3 = date '2010-02-01'

The hash calculation generates a string with: reportID + each 'p'-parameter + (optional 'm7') + URL hash seed,
where:

• reportID: either the numeric ID or the stored procedure name

• For each 'p' parameter: concatenate 'p' + parameter number + the urlencoded parameter value

• 'm' with value for report's folder (this parameter is optional)

• The URL hash seed from Environment settings

This would produce a string with '20p1200p2My%20paramsecret'. The hash is a sha1-value from the string
(d94be41fedd8ae66014a364120a020f01049d828).

The 'u' parameters are user changeable, so it will not be part of the hash.

The full url would be of form:

https://myserver.com/report.php?r=20&p1=200&p2=My
+param&h=d94be41fedd8ae66014a364120a020f01049d828

Calculating the URL with report name instead of report ID would be done from hash string:
'sp_DBR_myreportp1200p2My%20paramsecret'

79
Managing reports

https://myserver.com/report.php?r=sp_DBR_myreport&p1=200&p2=My
+param&h=5512f73a48693516e4837833b02e2ecd81bb5ced

If one wishes to hide the report procedure name and still use the portable URL, you
can use sp-parameter instead of the r-parameter and use md5-value from the report name.
md5('sp_DBR_myreport') = 3842a2ce71288a713015c033acf52c41m so the hash string would be
3842a2ce71288a713015c033acf52c41p1200p2My%20paramsecret

https://myserver.com/report.php?sr=3842a2ce71288a713015c033acf52c41m&p1=200&p2=My
+param&h=c14a8b3dd1cf741cf2c230e1bc0a4385b4453dc5

Embedding reports in a web page


To embed a report in your web site you can use the object tag. Example:

<object data="http://mysite.com/mydbr/report.php?
r=14&amp;u1=2009-10-01&amp;m=1&amp;h=123456789abcdef&amp;hdr=0"
type="text/html"
height="500px"
width="100%">
</object>

Direct accessible image reports

You can make a report which produces an image chart (ChartDirector / Graphviz) to produce the pure image
by adding &getchart=1 to URL. This will make the image accessible directly via an IMG tag.

This allows you to embed a report image from myDBR to your intra/extranet or into your own application without
any extra effort. Example:

<img src="http://mysite.com/mydbr/report.php?
r=14&amp;u1=2009-10-01&amp;m=1&amp;h=123456789abcdef&amp;getchart=1" />

Getting only the report object's content

You can also generate just the report object's content without any header information. This would allow you to
insert a myDBR result into your own webpage / application using a simple Ajax call. All styling can be done
in the receiving application.

Getting just the report object: Example:

<img src="http://mysite.com/mydbr/report.php?
r=16&amp;u1=2009-11-01&amp;m=1&amp;h=123456789abcdef&amp;embed=1" />

Using HTTP basic access authentication

myDBR also accepts connections using HTTP basic access authentication. In this method a username and
password are sent with the http request and instead of asking user to authenticate using the login screen,

80
Managing reports

myDBR uses the supplied username and password. Since basic access authentication sends the username
and password in plain text it is good practice to use a https-connection.

Using basic access authentication an extra header 'X-MYDBR-AUTH: 1' is required.

With basic access authentication, the username and password will be sent in HTTP headers. When myDBR
is using SSO authentication and a basic access authentication request is made, myDBR will redirect the
authentication call to use myDBR internal authentication. In case of myDBR internal authentication and LDAP
authentication no redirect is made and authentication is done through normal procedure.

An example call to obtain report output as a JSON object (&export=json added to the report call).

<?php

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, 'http://myserver.com/mydbr/report.php?
r=630&m=85&h=d46af7ad9a26bc574e10aa1b8c591a18892c57592&export=json');
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_HTTPAUTH, CURLAUTH_BASIC);
curl_setopt($ch, CURLOPT_USERPWD, 'username:password');
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-MYDBR-AUTH: 1'));
$data = curl_exec($ch);
curl_close($ch);

echo $data;

?>

You can also use HTTP basic access authentication when you schedule reports to run periodically. Use curl or
wget and put following command into your crontab / Windows Task Scheduler.

curl -u"username:password" -H "X-MYDBR-AUTH: 1" "http://myserver.com/mydbr/report.php?


r=630&m=85&h=d46af7ad9a26bc574e10aa1b8c591a18892c57592"

Statistics
myDBR gathers statistics on the reporting activity. Following information is gathered:

• User

• Report accessed

• Run start time

• Run end time

• Full query with parameters

The statistics are stored in the database table mydbr_statistics. The pre-installed reports
sp_DBR_StatisticsSummary and sp_DBR_StatisticsReport use this table for the reports.
Administrator can freely create new reports based on the data.

An administrator can/should use this information for

• Finding actively used reports

• Fixing slow reports

81
Managing reports

• Understanding which users / user groups use which reports

• Planning new reports

The administrator's 'Statistics summary' report (sp_DBR_StatisticsSummary) provides information on the


most active users, most active reports and the slowest reports.

The 'Statistics for a report' report (sp_DBR_StatisticsReport) provides information on an individual report.
It is used as a drill-down report for the 'Statistics summary'-report and behind the main screens Show Report
Statistics button (

).

Note
Statistics without run end time are reports whose execution has failed.

Localization
myDBR supports multiple languages both on myDBR's own UI and in produced reports.

Localizing myDBR's User Interface for your own language


myDBR's UI's localization strings are located in /interface/languages/-directory. To add support for a
new language add corresponding the language file. You can either fully localize the myDBR UI (including the
administrator layouts) or just the terms used in regular user's layouts. Terms starting a keyword 'MYDBR_A' are
user layout strings, the rest belong to administrator layouts.

A translation tool is provided in the 'Demo/Translation' section of the admin preferences. The tools shows which
terms needs to be translated and offers Google Translate's suggestions as a starting point. If you wish to
contribute a translation to be distributed as part of myDBR's official updates, please send your translation to
support@mydbr.com.

Multilingual support in myDBR


myDBR allows you to support multiple languages both in your report content and in the user interface. myDBR by
default selects an UI that matches the user's browser's language setting. Users can choose between available
languages by selecting one in the preferences.

• All report content

• Report categories

• Parameter names

• Report categories

• Report names

• Report description

• Login-screen notification

• Main-screen notification

• main_top.html

• main_sidebar.html

• Date names in reports (like select monthname(now()))

82
Managing reports

myDBR uses special formatted keywords with attached translations to do the localization. The notation used
in text to be translated is #{KEYWORD}. You define the KEYWORD in the localization dialog always available
from the localization icon

at top banner.

Handling dates in string

It is quite common that you return a string from database that contains dates. As the string concatenation
is already done in the server myDBR cannot use its regular way of determining datatypes. myDBR offers
a formatting option for this via special keyword 'DATE.FORMAT'. A string starting with DATE.FORMAT is
considered as a date formatting command that you can define in the localizations. You can define multiple
DATE.FORMAT options.

Example of a localized report

We'll create a simple localized report. The report is a chart with month names and text to be localized. First we'll
create the query and replace the text to be localized with keywords. In this case REQUESTS, LAST_YEAR and
THIS_YEAR will be localized. myDBR will automatically translate db-functions returning date names.

select 'dbr.chart', 'MSColumn', '#{REQUESTS}'

select DATE_FORMAT(month_day,'%b'), if (lastyear = 1, '#{LAST_YEAR}', '#{THIS_YEAR}') as


type, sum(value)
from production
group by 1, type
order by month desc, type;

We'll store the report (the report name and description can similarly be localized by defining a keyword) and
bring out the localization dialog:

83
Managing reports

When invoked, the localization dialog lets you choose from existing localizations or create a new one. When
the dialog is up with selected languages, you can use 'Translate' button to perform automatic translation using
Google Translate. Once the keyword is translated the report output will change based on the user's language
selection.

English:

Finnish:

To select languages available to users, select them in 'Environment settings' / 'Languages'

Using DATE.FORMAT
We'll define DATE.FORMAT.SHORT as a date formatting string. In the localization dialog we'll define the string
DATE.FORMAT.SHORT as a PHP date formatting string "%d %b %Y" as defined by PHP's strftime. You should
define individual formatting for each language.

select 'dbr.title', concat('This is localized title: #{DATE.FORMAT.SHORT:',cast(now() as


char(20)),'}');

This will produce the title "This is localized title: 24 Dec 2011" in English and '12 Gen 2012' in Italy.

Favorites
Favorites allow users to bookmark their most often used reports and have them listed in a Favorites-report
category. Favorites are marked with a star. Reports are added / removed from favorites by clicking the start.

84
Managing reports

Reports added as favorites are shown in the Favorites category and in the menu located in the top left corner.

If you wish to disable the favorites-functionality in your server, set $mydbr_defaults['favourites_enabled'] = false;
in you user/defaults.php

Customization
myDBR offers wide variety of options to customize the look and feel of the application.

Customize the Main Screen

The Main Screen offers a starting point for report launching.

Customizable items include:

Top header / dashboard

Fully customizable using user/main_top.html file. Can include dynamic content


(full reports, included image reports etc)

Sidebar

Meant for company logo / general greeting area. Fully customizable.

Notifications For short term notifications for users. Can be set inside the application without
changing any files.

Report categorization In addition to folders, myDBR can categorize reports / folders within one folder.
User selectable colors.

85
Managing reports

Customize the report


If you want to customize the report header and the footer, you can do it by changing the content of the user-
directory. Files in the directory are:

interface/themes Stylesheet defining the UI elements throughout the application.

user/reportheader.html Report header can include a reference to a company logo / text one wishes
to include in the report header.

user/images/ A file for your company logo. The logo size is defined in the user/
companylogo.png reportheader.html file.

user/defaults.php Override the myDBR's default values originally defined in mydbr/


defaults.php

user/userstyle.css Stylesheet to override / define own styles used in the application.

user/extension_init.php Extension initialization for user's extension's setting.

Customize the Top header / dashboard


The main view's top header (the dashboard) can include report content / single report elements like charts or
any HTML / JavaScript you want. The content to be shown will be placed to the user/main_top.html file.

To inlude a full report to the dashboard, you can use a predefined embed_url-JavaScript call which will take
the report URL as a parameter. When a report is embedded, add &embed=2 to the URL so that only the report
content is embedded.

<script type="text/javascript">
embed_url("http://myserver.com/mydbr/report.php?
r=59&m=45&h=84410e9a181a9f93ca85b1a1811351c415f1be85&embed=2");

86
Managing reports

</script>

If you want to just include images, you can include them directly using img-tag Use getchart-parameter to choose
which image to show. If the report just includes one image, use getchart=1.

<img src="report.php?
r=496&amp;u1=1&amp;m=60&amp;h=83e484f935d7b1d02d1fa07ca1b280a7ef9e1062&amp;getchart=1"
style="width:320px;height:150px;" alt="first" />

If you want to include different content with different language, you can use the localization featured. To do this,
put #{DASHBOARD} into the user/main_top.html, and define the desired content in the localization

at top banner.

Customize the PDF output


You can include your own logo into PDF output by adding the following lines to the user/defaults.php

$mydbr_defaults['export']['pdf']['logo'] = 'filename.jpg'; // where filename.jpg is an


image in user/images
$mydbr_defaults['export']['pdf']['logo_width'] = xx; // where xx is the logo width in
pixels

Using CSS for customization


myDBR allows report customization with your own css. Options for CSS customization include:

• Creating your own theme

• Adding own CSS definitions to user/userstyle.css

• Adding CSS inside a report

Creating your own theme

myDBR offers UI customization with themes. A theme is a CSS definition which defines UI elements for all
myDBR layouts. Creating a new css-file in interface/themes makes it available as a theme in the myDBR. To
create a new theme, use the existing ones as basis.

Adding own CSS definitions to user/userstyle.css

The file user/userstyle.css is used to define commonly used styles often shared with multiple reports. These
can be result set, row column and etc. styles.

Note
A report with reportID (r parameter in URL) has a DIV with classes "content report_519". "content" is
shared with all reports, "report_XXX" class allows styling an individual report in userstyle.css.

OEM customization
OEM customization allows you to whitelabel myDBR as your own solution. Branding allows you to add/replace
myDBR logos/texts with your own.

The application logo, application name, visibility of the header and the footer can be controlled from the
Environmental settings. Additionally, with OEM license, many of the customizable objects have additional
'oem_*' classes so you can style them with CSS.

87
Managing reports

Customizing OEM login screen

In addition to login notifications and userstyle.css, one can add HTML/JavaScript into the OEM login screen
by modifying the user/oem/login_bg.html file. The content of this file is inserted into div with class
oem_login_bg.

Scheduled tasks
Scheduled tasks allows for you to run reports unattended at defined schedule. You can control which reports
are run at which time within myDBR application.

Things you can do with scheduled tasks:

• Send regular emails from from reports (HTML, PDF, Excel)

• Send other type of messages based on report output: Push Notifications, SMS

• Run database maintenance work (summary table updates, delete/archieve old data, data checks)

Configuration

To run the scheduled tasks, you will create an entry for myDBR for the job scheduler (usually in your server:
cron in Unix/Linux and Task Scheduler in Windows) to call myDBR functionality scheduler.php. A sample entry
which would run every half an hour could look like this:
0,30 * * * * /opt/local/bin/wget -O - -q -t 1 https://myserver.com/mydbr/
scheduler.php > /dev/null 2>&1

The scheduler.php looks for jobs that needs to be run inside the myDBR and executes them. You should decide
the interval which the scheduler.php is run based on your need. The actual run itself, if no tasks needs to be
run, is light on resource usage. The tasks are run sequentially.

To configure the scheduled tasks environment, go to "Environment settings" / "Scheduled tasks" and define a
local myDBR user which is used to run the reports and IP's that are allowed to call (cron) the scheduler.php.
In the example, we have created a local myDBR use scheduler and allow the scheduler.php to be run from
the server only.

To configure the actual scheduled tasks, go to "Admin Tools" / "Scheduled tasks" and add a new task. A task is
added as a cron type interface which will determine what report is run at which time (the actual report execution
is done at time interval defined in the job scheduler's run). You can also disable defind tasks if

88
Managing reports

Synchronization
The function allows for you to synchronize changes from one myDBR installation to another. Objects to be
synchronized are:

• Reports

• Report parameters

• Report parameter queries

• Report permissions

• Report folder structure

• Report categories

• Templates

• Localizations

• Additional routines (stored procedures, functions)

Report related objects are synchronized based on report procedure creation date (or by folder if folder based
synchronzation is selected). This means that just changing report info does not trigger the synchronization.

89
Managing reports

Templates, Localizations and Additional routines are synchronized based on creation time.

Options
Created since / options

Will determine if reports synchronized are selected based on creation date or by the folder.

Match locations / Synchronization folder

When "Match locations" option is selected, the syncronized reports will be places in the same folder (based on
folder name) path as in the source system. If the folder path does not exists, it will be created.

If "Synchronization folder" option is selected, the folder (created if needed in main top level if needed) is used
to store the synchronized reports that do not exist in new server.

Combine permissions / Override permissions / Do not change permissions

When "Combine permissions" option is selected, the permissions for the report (and report path) will be
combined permissions from both source and target system if the report / path already exists.

With "Override permissions" permissions for report and report path will be copied from the source system. The
additional existing permissions will be removed.

With "Do not change permissions" no permission changes are done.

Note that the synchronization will not create user groups in target system. If user groups exist, they will be used.

The synchronization will by default synchronize all objects that match the search criteria. You can exclude
selected object from synchronization. The output from the synchronization is a SQL script you can execute in
the target installation.

Utilizing version control


myDBR offers a command line tool mydbr_sync which will extract myDBR reports and other objects to the local
filesystem. This will allow you to change reports in the server and extract the changes to the local filesystem
from where you can easily to put the files into your version control system. If you do not have direct access to
remote database you can use an SSH tunnel.

mydbr_sync is a java-program which requires Java 1.6 installed.

mydbr_sync separates different objects from mydbr-database and places them on separate directories.
mydbr_sync will by default produce following file structure into the directory where it is run:

.
### mydbr_sync.properties
### mydbr
### default
### functions
### procedures
### reports
### views

Usage
Go to the directory where you wish to extract mydbr-objects to. When you run mydbr_sync first time it will ask you
the configuration parameters and create the configuration file mydbr_sync.properties. Once the configuration
file exists you just run the mydbr_sync command.

java -jar mydbr_sync.jar [filename]

90
Managing reports

• where [filename] is the name of a database configuration file (default:mydbr_sync.properties)

• mydbr_sync will check if a configuration file exists and prompt for connection parameter to create one if needed

Sample configuration files


The user names and password must be the ones used in myDBR

for MySQL:

user=mydbr
pass=mydbr_pass
host=localhost
port=3306
database=mydbr_demo
db_type=mysql

for Microsoft SQL Server:

user=mydbr
pass=mydbr_pass
host=localhost
port=1433
database=mydbr_demo
db_type=mssql

for Sybase ASA:

user=mydbr
pass=mydbr_pass
host=172.16.125.139
port=5000
database=mydbr
db_type=sybase

Additional configuration settings


If you have a larger reporting structure and wish to separate different sub projects into separate directories, you
can define stored routine prefixes and define sub folders for file storage make the definition in your database
configuration file with following syntax

Each prefix is defined by prefix / subdir pairs:

prefix.your_id=your_routine_prefix

subdir.your_id=your_sub_folder_name

Additional definitions into mydbr_sync.properties:

prefix.1=sp_DBR_sales
subdir.1=sales

prefix.2=sp_DBR_development
subdir.2=development

prefix.3=fn_sales

91
Managing reports

subdir.3=sales

92
Chapter 6. Commands
Aggregate functions

Commands

dbr.sum - Calculates the sum of the selected column


dbr.min - Calculates the minimum value of the selected column
dbr.max - Calculates the maximum value of the selected column
dbr.count - Calculates the number of rows
dbr.avg - Calculates the average of selected column
dbr.sum.prefix - Set's the prefix to be used with dbr.sum
dbr.min.prefix - Set's the prefix to be used with dbr.min
dbr.max.prefix - Set's the prefix to be used with dbr.max
dbr.count.prefix - Set's the prefix to be used with dbr.count
dbr.avg.prefix - Set's the prefix to be used with dbr.avg
dbr.summary.text - Adds text to summary row
dbr.calc - Allows you to create calculation formulas to populate cells
dbr.summary.calc - Same as dbr.calc. Kept for compatibility with older versions
dbr.summary.options - Change the default aggregate calculation

Syntax

select 'dbr.sum', ColumnReference [, ColumnReference ...]


select 'dbr.min', ColumnReference [, ColumnReference ...]
select 'dbr.max', ColumnReference [, ColumnReference ...]
select 'dbr.count', ColumnReference [, ColumnReference ...]
select 'dbr.avg', ColumnReference [, ColumnReference ...]
select 'dbr.sum.prefix', ColumnReference, 'prefix'
select 'dbr.min.prefix', ColumnReference, 'prefix'
select 'dbr.max.prefix', ColumnReference, 'prefix'
select 'dbr.count.prefix', ColumnReference, 'prefix'
select 'dbr.avg.prefix', ColumnReference, 'prefix'
select 'dbr.summary.text', ColumnReference, [TextWithColumnReference]
select 'dbr.calc', ColumnReference|ColumnReference.aggregate, Formula[, summary_format[,
level]]
select 'dbr.summary.calc', ColumnReference, Formula
select 'dbr.summary.options', 'option' [, value]

Where:

ColumnReference see Column reference for syntax.

TextWithColumnReference Plain text or text with reference to column. Example: "Active users
[active_summary_column]"

Formula Any PHP compatible calculation that can include column references ([colref]). Example:
"([col1]+[col1])/100"

ColumnReference.aggregate An aggregate function applied to a column. Vertical aggregates are


calculated over rows:

• sum Calculates the sum of a column's values. Example: [colref.sum]

• min Calculates the minimum of a column's values. Example: [colref.min]

• max Calculates the maximum of a column's values. Example: [colref.max]

93
Commands

• count Calculates a count of the rows. Example: [colref.count]


Horizontal aggregates are calculated over data columns in crosstable for
each row:

• hsum Calculates sum crosstab column values. Example: [colref.hsum]

• hmin Calculates the minimum of a column's values. Example:


[colref.hmin]

• hmax Calculates the maximum of a column's values. Example:


[colref.hmax]

• hminus Calculates C1-C2-C3. Example: [colref.hminus]

• hcount Calculates count crosstab data columns. Example: [colref.hcount]

summary_format A format string to format dbr.calc on summary rows (for example "%.0f cases")

level Limitation into which summary levels / rows dbr.calc is calculated into: "0"=level 0 only, "1"=level 1
only, "<2"=rows, level 0 and 1

Explanation

With aggregate functions you can calculate a result set column's sum, minimum or maximum value and count
of individual rows. If the result set does include header levels, the calculation is also done for each break level.

dbr.summary.options include:

• limit_summary_level, level - Calculate summaries only to a certain level (0=total, 1=header lever 1 etc.)

• skip_single_line_summary - Do not put summary lines if summary level has only one row

Example use of an aggregate function

We'll calculate a summary for Items and the Weight column and also the maximum for Weight

select 'dbr.sum', 'Items', 'Weight'; /* Calculate sum from Items and Weight column */
select 'dbr.max', 'Weight'; /* Calculate sum from Items and Weight column */
select 'dbr.count', 'Title';

select Title, sum(Items), sum(Weight) as 'Weight'


from mydb.Exampledata
group by Title;

This will produce following result:

94
Commands

Including header levels in calculation

If an header level is included, the subtotals are also calculated:

select 'dbr.hdr', 'Year'; /* Sets the Year to be a header column */


select 'dbr.sum', 'Items', 'Weight'; /* Calculate sum from Items and Weight column */
select 'dbr.max', 'Weight'; /* Calculate sum from Items and Weight column */
select 'dbr.count', 'Title'; /* How many rows do we have? */
select 'dbr.summary.text', 'Year', 'Total';

select Year, Title, Items, Weight


from mydb.Exampledata
order by Year, Title;

Subtotals are calculated and the text appears in the summary row:

95
Commands

Calculations

dbr.calc command allows inserting formulas for a column. References to other columns is made by using the
Column reference. You can freely add any complex formula (with PHP syntax).

In addition to column references, one can use references to aggregate values (horizontal and vertical) by using
syntax [column.sum] for vertical aggregate values and [column.hsum] for horizontal aggregate values (crosstab
values). You can use this syntax for all aggregates (sum, min, max, count, avg).

When doing calculations, the formula is applied to all columns which are not null.

Basic calculation

In the example we want to have percentage calculated based on two columns. To reserve a place for the
calculation, a null value is placed in the query and it is given a column reference (percent).

select 'dbr.sum', 'ok', 'all';


select 'dbr.calc', 'percent', '[ok]/[all]*100';

select Group,
OK[ok],
allresults as 'All[all]',
null as '%[percent]'
from group_sessions;

96
Commands

Calculation applied to a crosstable


When a calculation formula is applied to the crosstable data value, it is performed for each dataset.

select 'dbr.sum', 'ok', 'all';


select 'dbr.hsum', 'ok', 'all';
select 'dbr.hdr', 'group';
select 'dbr.crosstab', 'session';
select 'dbr.colstyle', 'percent', '%.2f %';
select 'dbr.summary.text', 'group', 'Total';
select 'dbr.calc', 'percent', '[ok]/[all]*100';

select Group[group],
Session[session],
OK[ok],
allresults as 'All[all]',
null as '%[percent]'
from group_sessions;

Calculation with aggregate column reference


An aggregate column reference can refer to the aggregate value for the column. A normal use case is where
we need to calculate a percent share of each column of the total value.

The [Items.sum] reference in the formula refers to total sum of the Items.column.

select 'dbr.subtitle', 'Vertical summary';


select 'dbr.calc', 'percent', '[Items]/[Items.sum]*100';
select 'dbr.colstyle', 'percent', '%.0f %';
select 'dbr.sum', 'Items';

97
Commands

select Name,
sum(Items) as 'Items',
null as '%[percent]'
from mydata
group by Name;

Calculation with horizontal aggregate column reference


A horizontal aggregate column reference performs the calculation over the data columns in a crosstable. In the
example we'll calculate the share for each quarter of the total year for each row.

The [Items] refers to each items column (each quarter). The [Items.hsum] refers to the total column and
is independent from the actual Total column generated by the dbr.hsum-command. The dbr.hnull-command
generates a placeholder (a null column) for the percent-column.

select 'dbr.subtitle', 'Horizontal summary (Items.hsum)';


select 'dbr.crosstab', 'quarter';
select 'dbr.calc', 'percent', '[Items]/[Items.hsum]*100';
select 'dbr.hnull', 'percent';
select 'dbr.colstyle', 'percent', '[color:#888]%.0f %';
select 'dbr.sum', 'Items';
select 'dbr.hsum', 'Items';

select
Name,
f_quarter(thedate) as 'Quarter[quarter]',
sum(Items) as 'Items',
null as '%[percent]'
from mydata
group by Name, 2;

98
Commands

Combining calculation with horizontal and vertical aggregate column reference


The following example combines both calculation methods. The result differs from the earlier example in the
way that the total percent column will show the percentage of each row's total value from the grand total.

To achieve this, we'll use the dbr.hnull command to create a placeholder for the row total.

select 'dbr.subtitle', 'Horizontal summary (Items.hsum + Items.sum)';


select 'dbr.crosstab', 'quarter';

/* Calculate percent for data columns */


select 'dbr.calc', 'data_percent', '[Items]/[Items.hsum]*100';

/* Create a placeholder null-column for the total_percent */


select 'dbr.hnull', 'total_percent';

/* Calculate the total_percent */


select 'dbr.calc', 'total_percent', '[Items]/[Items.sum]*100';

/* We do not need to show the row percentage for each data column, only in total column */
select 'dbr.hidecolumn.data', 'total_percent';

/* Fade the percent columns a bit to make table more readable */


select 'dbr.colstyle', 'data_percent', '[color:#888]%.0f %';
select 'dbr.colstyle', 'total_percent', '[color:#888]%.0f %';
select 'dbr.sum', 'Items';
select 'dbr.hsum', 'Items';

select Name,
f_quarter(thedate) as 'Quarter[quarter]',
sum(Items) as 'Items',
null as '%[data_percent]',
null as 'Total %[total_percent]'
from mydata
group by Name, 2;

Titles / text
Commands
dbr.title - Set the report title. By default title is report's name
dbr.subtitle - Give a name to the result set in a report
dbr.text - Insert a free text element to report

99
Commands

Syntax

select 'dbr.title', 'Title text'


select 'dbr.subtitle', 'Subtitle text'
select 'dbr.text', 'Text' [, 'class']

Explanation

By default a report shows the report's name (name given when added to myDBR) as a title. It can be changed
with the dbr.title-command. The usual case is that reports parameters are included in the title.

If you have multiple result set's in the report, you may want to give them a title. This can be done using the
dbr.subtitle-command.

You can use dbr.text to insert a text element into the report. The text element's carriage returns are converted
to HTML <BR> elements. You are free to include HTML formatting in the text. The optional 'class' parameter
defines the CSS-style used for the text. If none is given, a default div.dbr_textbox is used. You are free to define
your own ones in user/userstyle.css.

Examples

create procedure sp_DBR_Titles(inFromDate date, inToDate date)


begin

select 'dbr.title', concat('Date range: ', inFromDate, ' - ', inToDate );


select 'dbr.subtitle', 'Film Categories';

select name, last_update


from mydb.category
where last_update between inFromDate and inToDate;

select 'dbr.subtitle', 'Languages';

select name, last_update


from mydb.language
where last_update between inFromDate and inToDate;

end

100
Commands

select 'dbr.text', 'Default text';


select 'dbr.text', "'box'-style textbox", 'box';
select 'dbr.text', "'comment'-style textbox", 'comment';

101
Commands

If you wish to add your own text styles add the CSS definition to user/userstyle.css.

Applying styles
myDBR offers commands for formatting the individual report elements if the default formatting is not sufficient.

Styles can alter all the visual elements of the data: formatting, color (background, foreground), font etc. Styles
can be applied to several elements in the result set: individual rows, columns, header and the footer. myDBR
supports global styles that can be shared between reports. Styles can also be defined dynamically in a report. In
order to keep the report's look and feel consistent, it is recommended that styles from parameters are to be used.

Commands ending with "class" take a CSS class as a parameter. One can define a CSS class with dbr.css-
command or by adding the class definition in the user/userstyle.css -file where the definition is available to
every report.

Common use cases for formatting are:

• Hiding some columns (in order still to use them when passing parameters to another report via report linking)

• Formatting columns (content formatting, foreground/background colors, fonts)

• Formatting the report rows (colors, fonts)

• Formatting individual cells (colors, fonts, formatting)

• In addition to this, myDBR offers ways to format result set headers and footers

myDBR has global styles which can be applied to elements via the mydbr_style function. See definition of
global of Styles at Preferences.

Note
mydbr_style is a database function which accesses the style-table from the myDBR. When using the
function in MS SQL Server, Sybase ASE or SQL Anywhere, please use the syntax: dbo.mydbr_style()

Commands

dbr.hidecolumns - Hide the number of columns at the end of the result set
dbr.hidecolumn - Hide individual columns which can be anywhere in the query
dbr.showcolumn - Show individual columns that were automatically hidden
dbr.rowstyle - Report row's CSS style. A column in the query contains the CSS style for the row
dbr.rowclass - Report row's CSS class. A column in the query contains the CSS-classname for the row
dbr.colstyle - Report column's style, where a style is a combination of printf formatting/CSS-style
dbr.colclass - Report column's CSS class. Adds a CSS-class to a specified column
dbr.cellstyle - Adds CSS-style to individual cells based on style in another column. This allows value based
formatting
dbr.cellclass - Adds CSS-class to individual cells based on style in another column. This allows value
based formatting
dbr.cellformat - Report cells' printf format. Format column with formatting from another column. Allows
formatting cells differently in the same column in different rows
dbr.hideheader - Hide the headers in result set
dbr.headerstyle - Header's style
dbr.header.colclass - Header-column's CSS class
dbr.footerstyle - Footer's style
dbr.footer.colclass - Footer column's CSS class'
dbr.footer.colstyle - Footer's style for specific column
dbr.footer.cellclass - Set footer's CSS class based on data on another footer column
dbr.footer.cellstyle - Set footer's CSS style based on data on another footer column
dbr.resultclass - Add custom CSS class to result table

102
Commands

dbr.html5data - Put a column to another columns data-xxx attribute instead of a column

Syntax

select 'dbr.hidecolumns', ColumnReference / nbr of columns from right to hide


select 'dbr.hidecolumn', ColumnReference [, ColumnReference...]
select 'dbr.showcolumn', ColumnReference [, ColumnReference...]
select 'dbr.rowstyle', ColumnReference
select 'dbr.rowclass', ColumnReference
select 'dbr.colstyle', ColumnReference, columnstyle[, calc]
select 'dbr.colclass', ColumnReference, css_classname
select 'dbr.cellstyle', ColumnReference, CSSStyle_ColumnReference
select 'dbr.cellclass', ColumnReference, CSSclass_ColumnReference
select 'dbr.cellformat', ColumnReference, ColumnFormat_ColumnReference
select 'dbr.hideheader'
select 'dbr.headerstyle', rowstyle
select 'dbr.header.colclass', ColumnReference, css_classname
select 'dbr.footerstyle', rowstyle
select 'dbr.footer.colclass', ColumnReference, css_classname
select 'dbr.footer.colstyle', ColumnReference, columnstyle
select 'dbr.footer.cellclass', ColumnReference, CSSclass_ColumnReference
select 'dbr.footer.cellstyle', ColumnReference, CSSstyle_ColumnReference
select 'dbr.resultclass', 'myclass'
select 'dbr.html5data', 'ColumnReferenceTo', 'ColumnReferenceFrom', 'xxx'

Column hiding
Hidden columns are used to include ID values which may not necessary to be shown to the user, but are used
for report linking / other functionality or hidden columns are used for calculation purposes. Columns can be
hidden using dbr.hidecolumns and dbr.hidecolumn commands. The dbr.hidecolumns command hides number of
columns from the end where ColumnReference marks the first column to be hidden. dbr.hidecolumn command
can be used to hide individual commands.

Examples

/*
Show only the customer name for the user, but link the report on customer ID
We'll hide 1 column from the end
*/
select 'dbr.report', 'sp_DBR_MoreCustomerInfo', 'ID=ID';
select 'dbr.hidecolumns', 'ID';

select Name, ID
from mydb.Customer;

Define a column style


On tabular reports you may have a need to format a column differenty from the default style. You can apply
a style to the command by using the dbr.colstyle - command. The command takes one parameter, which is
the style definition. myDBR offers global styles that can be shared between the reports. These styles can be
accessed using the built-in mydbr_style-function. Alternatively, use can simply use ad-hoc/dynamic styles as a
parameter. It is recommended that you use global styles when you do not need dynamic styling.

Column style can be used to format an image when fetching image blob from the database.

Column style can also contain a calculation format (with PHP syntax). This comes handy for example in cases
where you have number of rows with decimals and you want to show rounded numbers to the user, but still
want to maintain high accuracy when calculating summary values.

103
Commands

Column style format

The column style has a format consisting of:

Positive value style [; Zero value style [; Negative value style] ]

The format of each of these (positive, zero and negative) styles is:

[CSS style definition] printf arguments for the value

You can omit the CSS or printf part of the style if you do not need one.

The column style when fetching image blobs directly from the database is:
[image CSS-style]image

Examples

In the example we have defined a style called 'AlternateColorDecimal' in Preferences. The style is defined as:

[color: green]%.2f; ;[color: red;]%.2f

Positive numbers are in green with 2 decimals, zero is set to space (=blank) and negative numbers are in green
with 2 decimals:

/*
Apply a predefined style for the column Total
*/
select 'dbr.colstyle', 'Total', mydbr_style('AlternateColorDecimal');

select Name, Total


from mydb.Customer;

And the result shows numbers formatted accordingly:

Other examples:

• A decimal number with just one decimal in green:

[color: green]%.1f

• Text on a yellow background

[background-color: yellow;]

• Integer number without the thousand separator (by default the thousand separator from Environment settings
is used)

%d

104
Commands

• Limiting column width (200px) and preventinf line wrapping without losing the information for export. Will put
an ellipsis on the end of column if the column is too wide

[overflow:hidden; white-space: nowrap; text-overflow:ellipsis; width: 200px;max-width:


200px;]

Summary calculation with column style

Summary calculation is always made using full decimal numbers even when the row values are rounded to be
less accurate.

Showing full accuracy in the summary column

/*
Apply a style for the column to display the value in one decimal. The summary
calculation is done using full accuracy
*/
select 'dbr.colstyle', 'Rounded', '%.1f';
select 'dbr.sum', 'Original', 'Rounded';

select item_value as 'Original', item_value as 'Rounded'


from mydb.mydata;

And the result shows numbers formatted accordingly:

Define a row style

You can also define a style for an individual row. This is not as common as column styling, but can be used when
individual rows need different formatting. Since a row can contain multiple columns with different datatypes,
row styles cannot format the content, just the appearance. Styling the rows also differs in the way that the style
defined in the data itself while dbr.rowstyle -command refers to the column containing the style.

Examples

/*
Some rows are drawn with white-on-red
*/
select 'dbr.rowstyle', 'rowstyle';

select 'First row' as 'Col 1', '' as 'Col 2[rowstyle]'


union all
select 'Second row', mydbr_style('WhiteOnRed')
union all
select 'Third row', '';

Will produce a row with set attributes. Usually the style column is placed into the end of the selected list and
it is hidden.

105
Commands

Example row styles:


Row style is simply a CSS-format string.

CSS style definition

Some example styles:

• White text on red background:

color: white; background-color: red;

• Big font

font-size: 18px;

Define a cell style or class


With the cell style you are able to define a style for each cell in the report. Similarly one can use CSS-class
to define the style

Examples
/*
Color red cells whose value is less than 14. Other cells will be green
*/
select 'dbr.crosstab','Month';
select 'dbr.hidecolumns', 'style';
select 'dbr.cellstyle', 'value', 'style';

select name,
Month,
value as '[value]',
if (value<14,'color:red','color:green') as 'style'
from mydb.mydata;

Same as previous, now using the dbr.cellclass with predefined classes redclass and greenclass

/*
Color red cells whose value is less than 14. Other cells will be green
*/
select 'dbr.css', '.redclass {color:red;} .greenclass {color:green;}';
select 'dbr.crosstab','Month';
select 'dbr.hidecolumns', 'class';
select 'dbr.cellclass', 'value', 'class';

select name,
Month,
value as '[value]',
if (value<14,'redclass','greenclass') as 'class'
from mydb.mydata;

Both will have similar output

106
Commands

Hiding the header from a result table


If you want to display only the data, but not the column header in the tabular report, this can be done with the
dbr.hideheader-command. The command takes no parameters.

Examples
/* Don't show the header */

select 'dbr.hideheader';

select Year, Title, Inventory, Items


from mydb.Exampledata
order by Year, Title;

Will produce the result set without the header

Header and footer styles


Header styles can be defined using a css style or css class (dbr.header.colclass- and dbr.headerstyle-
commands).

Footer can have a constant style shared among all footers (subtotals and totals). These can be set using
commands dbr.footer.colstyle and dbr.footer.colclass. You can also format footer columns based on footer
values using dbr.footer.cellclass and dbr.footer.cellstyle.

Examples
/* Turn the headers background to yellow */

select 'dbr.headerstyle', 'background-color: black;';

select Year, Title, Inventory, Items


from mydb.Exampledata
order by Year, Title;

Will produce the result set with black header

107
Commands

Custom CSS class for result tables


If you wish to add a custom style to result table you can add a CSS style for it. Define the style in userstyle.css
(or embed it into report using 'dbr.html:').

Examples

We'll make a custom box for invoice header. We'll use pageview to output the data and we'll create a custom
CSS for the object. First we'll create the style in userstyle.css overriding the default styles.

table.invoicebox {
border: 1px solid black;
}

table.invoicebox tr {
border: none;
}

table.invoicebox td {
background-color: #EFEFEF;
}

/* Turn the headers background to yellow */

select 'dbr.pageview';
select 'dbr.resultclass', 'invoicebox';

select nbr as 'Invoice number',


invoice_date as 'Date',
interest as 'Interest';
from invoices
where nbr = 1

Will produce the desired result

Formatting columns and footers based on data


Format the data cell and footer column format based on data.

-- Define the styles


select 'dbr.css', '.text_green {color:green}';
select 'dbr.css', '.text_red {color:red}';

-- Format data cells and the footer alike


select 'dbr.cellclass', 'Diff', 'color';
select 'dbr.footer.cellclass', 'Diff', 'color';

select 'dbr.sum', 'Value', 'Budget';


select 'dbr.calc', 'Diff', '[Value] - [Budget]';

-- Calculate the CSS class to be used


select 'dbr.calc', 'color', "[Value]>=[Budget] ? 'text_green' : 'text_red'";

select Date, Value, Budget, null as Diff, null as 'color'

108
Commands

from mydata;

Using html5 data-* attributes


With the dbr.html5data-command one can turn a column into html5 data attrbute. This can be used if JavaScript
is used to acccess the data.

Examples

/* Turn the headers background to yellow */

select 'dbr.html5data', 'Title', 'data_code', 'code';

select Title, data_code


from mydb.Exampledata;

Will produce a table cell with 'data-code' attribute.

<td data-code="a3-2x" class="cell">180</td>

The data can be accessed with pure JavaScrpt element.dataset.code or using jQuery
$(element).data('code').

Fetching images from the database


We'll set the image a CSS style 'width:150px'. The constant 'image' tells myDBR to determine the image fromat
from the incoming image data stream.

select 'dbr.colstyle', 'image_data', '[width:150px]image';

select image_data
from images;

select item_value as 'Original', item_value as 'Rounded'


from mydb.mydata;

Calendar
Calendar allows for you to create fully featured calendar from your data. myDBR utilizes FullCalendar for this.
Calendar data can be fetched dynamically via Ajax or directly within the main report.

109
Commands

Commands
dbr.calendar - Create a calendar from a result set or dynamically via Ajax
dbr.calendar.report - Define the Ajax report for calendar data
dbr.calendar.options - Set calendar options

Syntax

select 'dbr.calendar', [max_width [, default_date]]


select 'dbr.calendar.report', 'sp_DBR_calendar_ajax' [, param1[, param2..]]
select 'dbr.calendar.options', option, value

The 'option' can be 'event.style' or any FullCalendar option. Here are the most commonly used ones. See
FullCalendar documentation for more.

• 'event.style', 'css style' - default CSS style for event

• 'editable', editing_type , 'sp_DBR_editing_report', 'ColumnRef'[, 'ColumnRef'...] - Set entries editable,


possible editing types 'all/""' | 'start' | 'duration'

• 'new', 'new_buttons_class', number_of_datetime_parameters - Connect day click to "New calendar entry"-


button

• 'selectable', 1 - Allows to create calendar events by painting the days/hours. Is connected to "New calendar
entry"-button.

• 'event.editable', ColumnRef - Override the 'editing type'. Possible values from the columb 'all', 'start',
'duration' and ''. In 'all' both start and duration can be edited, if '' no editing is allowed.

• 'event.id', ColumnRef - Define event's ID. Can be used with FullCalendar JavaScript API

• 'height', pixels - (FullCalendar) height of the Calendar in pixels

• 'weekends', 1 | 0 - (FullCalendar) show / hide weekends

• 'weekNumbers', 1 | 0 - (FullCalendar) show / hide weeknumbers

• 'firstDay', 0-7 - (FullCalendar) Start of the week (the default is determined by the locale)

• 'timeFormat', format - (FullCalendar) time format ('h:mm', 'h(:mm)t'), default is determined from myDBR time
format

• 'defaultView', viewname - (FullCalendar) one from the available views. Defaults: month, agendaWeek,
agendaDay and listMonth

• 'slotDuration', duration - (FullCalendar) The time steps in the calendar. Default "00:30:00" (30 minutes)

Data fectched dynamically via Ajax


Fetching data dynamically (via Ajax) allows for browsing unlimited date range. The calendar content is fetched
when needed as user navigates the calendar. The report consists of a main report introducing the calendar and
the report responsible of fetching the data.

Calendar level options / commands are put in the main report. These include for example height, weekends,
weekNumbers etc.

110
Commands

create procedure sp_DBR_calendar( in_calendar_id int)


begin

select 'dbr.calendar', 800;


-- Define the calendar data report
select 'dbr.calendar.report', 'sp_DBR_calendar_data', in_calendar_id;

-- Show the calendar with result set, content does not matter
select 'dummy';

end;

The calendar dynamic data report consist of a report which has startdate and enddate as first two parameters
(additional parameters can be passed). The returning result set contains the event's starting datetime, ending
datatime and the calendar text entry. Additional columns can be used to create linked reports / URL's for the
calendar entry.

Entries do not show times if both start and end datetimes have time part '00:00:00' or start has time part '00:00:00'
and end is null. These are considered full day entries.

dbr.cellstyle and dbr.cellclass can be used to style the individual entry. For example, the "Birthday party" entry
is styled with 'background:red;color:white'.

All commands/options that refer to the result set's columns or are calendar entry level commands (like dbr.report,
dbr.url, editable-option event.editable-option), needs to be put in the calendar's dynamic data report, not into
the main report.

create procedure sp_DBR_calendar_data(


in_from date,
in_to date,
in_calendar_id int )
begin

select 'dbr.cellstyle', 'entry', 'style';


select 'dbr.report', 'sp_DBR_entry_actions', '[entry]', 'in_id=id', "popup";

-- Select all entries which are inside the current range. Optional criteria (like
in_calendar_id) can be used.
select datetime_from, datetime_to, entry, style, id
from mydb.calendar
where calendar_id=in_calendar_id and
cast(datetime_from as date) <= in_to and ifnull(cast(datetime_to as date),in_from) >=
in_from;

end

111
Commands

Data fectched directly

You can also create a calendar with single report if you have limited date range (no additional data is fetched).
This can be used when only limited number of entries are fetched. Otherwise the recommended way is to use
the dynamic data fetching.

create procedure sp_DBR_calendar( in_calendar_id int)


begin

select 'dbr.calendar', 800;

-- Override the header set in defaults.php to remove the prev/next month buttons
select 'dbr.calendar.options', 'header', '{"left":
"today","center":"title","right":"month,agendaWeek,agendaDay,listMonth"}';

select datetime_from, datetime_to, entry, style


from mydb.calendar
where calendar_id=in_calendar_id and
cast(datetime_from as date) <= in_to and ifnull(cast(datetime_to as date),in_from) >=
in_from;

end

Editable events

By using the 'editable'-option, you can make the calendar events editable. User can by default adjust the start
time (drag and move events) and adjust the duration (resize the end time). You can define what user can do,
by setting the editing_type parameter ('all' or '' for both start end duration , 'start' for just starttime change and
'duration' for end time editing). You can also define the editing capability for each individual entries by using
the 'event.editable'-option.

Calendar event adjust duration:

112
Commands

Calendar event adjust the start time:

In order to create new events or delete existing ones, use a linked report.

The calendar editing report will automatically add starttime and endtime as last parameters. Other parameters
can be defined in 'editable'-option after the editing report name.

create procedure sp_DBR_calendar( in_calendar_id int)


begin

select 'dbr.calendar', 800;

select 'dbr.calendar.options', 'editable', '', 'sp_DBR_calendar_edit', 'id';

select 'dbr.calendar.report', 'sp_DBR_calendar_editable_data', in_calendar_id;


-- Show the calendar with result set, content does not matter
select 'dummy';

end

The data report can override the default editable for each entry via event.editable option. The column referenced
can contain '' for no editing, 'start' to allow start time to be edited, 'duration' to edit the event duration and 'all'
to enable both start time and duration editing.

create procedure sp_DBR_calendar_editable_data(in_from date, in_to date, in_choose int)


begin

-- All options that refer to columns need to be placed into the data report
select 'dbr.cellstyle', 'entry', 'style';
select 'dbr.calendar.options', 'editable', '', 'sp_DBR_calendar_edit', 'id',
'datetime_from', 'datetime_to';

-- Set editing capability per event


select 'dbr.calendar.options', 'event.editable', 'editable';

-- Optionally set the id which can be used with the FullCalendar JavaScript API
select 'dbr.calendar.options', 'event.id', 'id';

-- Add capability to delete an event


select 'dbr.report', 'sp_DBR_calendar_delete','[entry]', 'in_id=id', "misc[]",
'"dbr.html:<span style="color:red">Delete event</span>"';

select datetime_from, datetime_to, entry, style, editable, id


from mydb.calendar

113
Commands

where calendar_id=in_calendar_id and


cast(datetime_from as date) <= in_to and ifnull(cast(datetime_to as date),in_from) >=
in_from;

end

The sp_DBR_calendar_edit report would then have three paramerer: id, start time, and end time.

create procedure sp_DBR_calendar_edit(


in_id int,
in_from datetime,
in_to datetime
)
begin

update mydb.calendar
set
datetime_from = in_from,
datetime_to = in_to
where id=in_id;

end

You can also reject the editing inside the editing routine and/or pass text that will be show to user. If the text
starts with 'reject:', the UI will undo the editing and move/resize the event back to original position. If a text
without 'reject:' is selected, the text will be shown to the user and the event will be accepted by the UI.

create procedure sp_DBR_calendar_edit(


in_id int,
in_from datetime,
in_to datetime
)
begin

declare v_min_time datetime;

select min_time into v_min_time


from mydb.open_slots;

if (in_from < v_min_time) then


select 'reject:The selected timeslot is closed';
else
update mydb.calendar
set
datetime_from = in_from,
datetime_to = in_to
where id=in_id
end if;
select 'Event succesfully moved';
end if;

end

Add new events to calendar


You can add new events to the calendar by using a linked report. Add a button to the main report whose target
is a dynamic div (as example 'misc').

select 'dbr.button', 'New';

114
Commands

select 'dbr.report', 'sp_DBR_calendar_event_new', 'misc[]';


select 'Dummy';

The 'sp_DBR_calendar_event_new' linked report asks the datetimes and the entry text as parameter and after
insert refreshes the Ajax-calendar.

create procedure sp_DBR_calendar_event_new(


in_from datetime,
in_to datetime,
in_entry varchar(120)
)
begin

insert into mydb.calendar ( datetime_from, datetime_to, entry )


values ( in_from, in_to, in_entry );

select 'dbr.javascript', "$('.mycal').fullCalendar( 'refetchEvents' )";

end

Remove an event from the caledar


Calendar events have an ID you can set using the event.id-option which you define when the events are fetched.

select 'dbr.button', 'New';

select 'dbr.report', 'sp_DBR_calendar_event_new', 'misc[]';


select 'Dummy';

The 'sp_DBR_calendar_event_new' linked report asks the datetimes and the entry text as parameter and after
insert refreshes the Ajax-calendar.

create procedure sp_DBR_calendar_event_delete(


in_entry varchar(255)
)
begin

delete
from mydb.calendar
where id=in_id;

select 'dbr.javascript', "$('.mycal').fullCalendar( 'refetchEvents' )";

end

Full calendar functionality with connection to the "New calendar entry"-button


When you add a "New calendar entry"-button to the report, you can also automatically connect calendar internal
actions to this button. These internal actions include:

• Doubleclick on the calendar to create new entry

• Paint (click and drag with mouse) into the calendar to create new entry

Create the main report and set calendar date to be fecthed dynamically. Add

create procedure sp_DBR_calendar( in_calendar_id int)

115
Commands

begin

select 'dbr.javascript','
function confirmdel(obj) {
return confirm("Are you sure you want to delete the entry?");
}';

select 'dbr.calendar', 800;


-- Define the calendar data report
select 'dbr.calendar.report', 'sp_DBR_calendar_data', in_calendar_id;

-- Bind to 'newentry' button and tell that the new calendar entry report has two datetime
parameters
select 'dbr.calendar.options', 'new', 'newentry', 2;
-- Allow user to create new calendar entries by painting (click and drag with mouse)
select 'dbr.calendar.options', 'selectable', 1;

-- Show the calendar with result set, content does not matter
select 'dummy';

-- Create the "New calendar entry"-button with newentry-class (and add plus-character to
the button)
select 'dbr.button', '<i class="fa fa-plus" aria-hidden="true"></i> New calendar entry',
'newentry button';
select 'dbr.report', 'sp_DBR_calendar_event_new', 'misc[]';
select 1;

end;

create procedure sp_DBR_calendar_data(in_from date, in_to date, in_id)


begin

select 'dbr.cellstyle', 'entry', 'style';


select 'dbr.calendar.options', 'editable', '', 'sp_DBR_calendar_edit', 'id',
'datetime_from', 'datetime_to';
select 'dbr.calendar.options', 'event.editable', 'editable';

select 'dbr.report', 'sp_DBR_calendar_delete','[entry]', 'in_id=id', "misc[]",


'callbefore=confirmdel', '"dbr.html:<span style="color:red">Delete event</span>"';

select 'dbr.calendar.options', 'event.id', 'id';

select datetime_from, datetime_to, entry, style, editable, id


from mydb.calendar
where calendar_id=in_id
cast(datetime_from as date) <= in_to and cast(datetime_to as date) >= in_from;

Cross tabulation
Commands
dbr.crosstab - Turn a table report into a cross tabulation report. The first parameter is the crosstable column,
the optional second parameter marks the last data column inside a crosstable.
dbr.hsum - Calculate horizontal sum in a cross tabulation report
dbr.hmin - Calculate horizontal minimum in a cross tabulation report
dbr.hmax - Calculate horizontal maximum in a cross tabulation report
dbr.hminus - Calculate horizontal value with formula Col1 - Col2 - Col3...
dbr.hnull - Creates a placeholder for horizontal column used with dbr.calc
dbr.hcount - Calculate number of values horizontally in a cross tabulation report
dbr.havg - Calculate horizontal average in a cross tabulation report

116
Commands

dbr.hidecolumn.data - Allows hiding crosstable data columns, keep summary column. Used with dbr.calc
dbr.hidecolumn.set.data - Allows hiding crosstable data columns based on data CrossTabSet name
dbr.hidedatacolumn - Same as dbr.hidecolumn.data, kept for compatibility
dbr.hidecolumn.data.all - Hide all crosstable data columns, keep summary column.
dbr.hidecolumn.summary - Allows hiding crosstable summary columns, keeping data columns. . Used with
dbr.calc
dbr.crosstab.title - Redefine the default title for horizontal summary column
dbr.crosstab.order - Set the order of the cross tabulation columns
dbr.crosstab.col - Predefine the cross tabulation columns
dbr.crosstab.options - Add crosstab option
dbr.crosstab.col.title - Set column title for crosstab horizontal summary column
dbr.crosstab.col.style - Set columnstyle for crosstab horizontal summary column
dbr.crosstab.header - Add additional header group in crosstab
dbr.crosstab.header.col - Predefine the 2nd level cross tabulation header columns defined in
dbr.crosstab.header

Syntax

select 'dbr.crosstab', ColumnReference [, ColumnReference]


select 'dbr.hsum', ColumnReference, [ColumnReference... ]
select 'dbr.hmin', ColumnReference, [ColumnReference... ]
select 'dbr.hmax', ColumnReference, [ColumnReference... ]
select 'dbr.hminus', ColumnReference, [ColumnReference... ]
select 'dbr.hnull', ColumnReference, [ColumnReference... ]
select 'dbr.hcount', ColumnReference, [ColumnReference... ]
select 'dbr.havg', ColumnReference, [ColumnReference... ]
select 'dbr.hidecolumn.data', ColumnReference, [ColumnReference... ]
select 'dbr.hidecolumn.set.data', 'CrossTabSet', ColumnReference, [ColumnReference... ]
select 'dbr.hidedatacolumn', ColumnReference, [ColumnReference... ]
select 'dbr.hidecolumn.data.all' {, 1/0 }
select 'dbr.hidecolumn.summary', ColumnReference, [ColumnReference... ]
select 'dbr.crosstab.title', 'title'
select 'dbr.crosstab.order', 'asc'|'desc'
select 'dbr.crosstab.col', col_value1, [col_value2... ]
select 'dbr.crosstab.options', 'no_null_data'
select 'dbr.crosstab.col.title', ColumnReference, 'title'
select 'dbr.crosstab.col.style', ColumnReference, columnstyle
select 'dbr.crosstab.header', ColumnReference
select 'dbr.crosstab.header.col', col_value1, [col_value2... ]

Explanation
In cross tabulation the result set's data is separated into header and data sections divided by a cross tabulation
column. Header columns (left from cross tabulation-column) will determine the distinct rows in the final result
set. The data columns (derived for the cross tabulation-column) will be repeated to the right. By defining the
second parameter in the dbr.crosstab-command, header columns can also appear on the right side of cross
tabulation data columns.

Examples
Say we have basic data set:

select RepArea as 'Reporting area',


Period,
last_year as 'Last year',
this_year as 'This year',
next_year as 'Next year'
from mydb.ProductionSummary;

117
Commands

We can determine the different parts of the result set:

By defining the column 'Period' as a cross tabulation column, the distinct values in the column are calculated
as group columns and the data columns are calculated underneath each group column.

/*
Define the Period as a cross tabulation column
*/
select 'dbr.crosstab', 'Period';

select RepArea as 'Reporting area',


Period,
last_year as 'Last year',
this_year as 'This year',
next_year as 'Next year'
from mydb.ProductionSummary;

Calculating column and row summaries


You can apply the aggregate functions over row and column values. For columns use: dbr.sum, dbr.min,
dbr.max, dbr.avg or dbr.count. For rows use dbr.hsum, dbr.hmin or dbr.hmax.

myDBR handles the hard work by doing the calculation on applicable columns and adds summary columns
if necessary. If the data column has no name (set to empty string) the header part of it will be hidden (see
example below).

select 'dbr.crosstab', 'Quarter';


select 'dbr.sum', 'Items','Weight';

118
Commands

select 'dbr.crosstab.title', '2008 total';


select 'dbr.hsum', 'Items','Weight';

select Name,
concat(year(InsertDate), ' Q',quarter(InsertDate)) as 'Quarter',
sum(Items) as 'Items',
sum(Weight) as 'Weight'
from mydb.Production
group by Name, 2;

You can also apply calculate multiple horizontal aggregates for a column by duplicating the column and hiding
the datacolumn. A datacolumn is the repeated crosstab-data column. In the example multiple multiple horizontal
aggregates are calculated and styled:

/* Set titles for horizontal aggregate columns */


select 'dbr.crosstab.col.title', 'value', 'Avg';
select 'dbr.crosstab.col.title', 'sum', 'Sum';
select 'dbr.crosstab.col.title', 'count', 'Count';
/* Style the horizontal average column */
select 'dbr.crosstab.col.style', 'value', '[color:red]%.1f';
/* Style the horizontal sum column */
select 'dbr.crosstab.col.style', 'sum', '[color:green]';

select 'dbr.crosstab', 'Quarter';

/* Horizontal aggregates */
select 'dbr.havg', 'value';
select 'dbr.hsum', 'sum';
select 'dbr.hcount', 'count';

/* Show the sum and count columns only in the horizontal summary section */
select 'dbr.hidecolumn.data', 'sum';
select 'dbr.hidecolumn.data', 'count';

/* Vertical aggregates */
select 'dbr.sum', 'value';
select 'dbr.sum', 'sum';
select 'dbr.sum', 'count';

select

119
Commands

Name,
concat('Q',quarter(InsertDate)) as 'Quarter',
sum(Items) as '[value]',
sum(Items) as '[sum]',
sum(Items) as '[count]'
from TestTable
group by Name, 2
order by Name, 2;

Define the crosstab column header order


If you need to define the order of existing crosstab column headers, you can use dbr.crosstab.order-
command.

select 'dbr.crosstab', 'Month';


select 'dbr.crosstab.order', 'asc';
select 'dbr.sum', 'value';
select 'dbr.hsum', 'value';

select Name,
Month,
Value as '[value]',
from mydb.monthlyvalues
order by Name;

If your data does not include all crosstab column headers you want the report to show, use the
dbr.crosstab.col-command.

Predefine data columns


By predefining the data columns you can define which data columns are shown in cross tabulation report (and
in which order). This is useful in cases where you already know what cross tabulation columns you want in the
report (series of months, fixed quarters etc.) and/or you want to include columns that do not exist in data itself.

select 'dbr.crosstab', 'Month';


select 'dbr.sum', 'value';
select 'dbr.hsum', 'value';

select Name,
Month,
Value as '[value]',
from mydb.monthlyvalues
order by Name;

120
Commands

In the example we'll create a report with a monthly distribution. The data in the example does not include all
the months (1-12).

In the example the months were derived from the fetched data. This includes both order and the actual
values. In order to define all the months (1-12) and also define the order of the columns you can use the
dbr.crosstab.col-command.

select 'dbr.crosstab', 'Month';


select 'dbr.crosstab.col', 1,2,3,4,5,6,7,8,9,10,11,12;
select 'dbr.sum', 'value';
select 'dbr.hsum', 'value';

select Name,
Month,
Value as '[value]',
from mydb.monthlyvalues
order by Name;

As a result you'll get a result where all the months are defined and are defined in logical order.

If you have a dynamic number of columns (for example the report parameter contains a date range), you can also
issue the dbr.crosstab.col-command multiple times. Each subsequent dbr.crosstab.col-command
will add columns to final report.

select 'dbr.crosstab', 'Month';


declare iMonth int;

set iMonth = 1;
while( iMonth <= inMonthParameter ) do
select 'dbr.crosstab.col', iMonth;
set iMonth = iMonth + 1;
end while;

select 'dbr.sum', 'value';


select 'dbr.hsum', 'value';

121
Commands

select Name,
Month,
Value as '[value]',
from mydb.monthlyvalues
order by Name;

If the report query will produce data columns not defined in predefined data columns, the columns will be added
to the end of column list.

Full cross tabulation example


By defining the column 'Period' as a cross tabulation column, the distinct values in the column are calculated
as group columns and the data columns are calculated underneath each group column.

/*
Define the Period as a cross tabulation column
Add column and horizontal sums
Name the crosstab column
*/
select 'dbr.crosstab', 'Period';
select 'dbr.sum', 'last', 'this', 'next';
select 'dbr.hsum', 'last', 'this', 'next';
select 'dbr.crosstab.title', 'Total H1';
select 'dbr.summary.text', 'area','Total';

select RepArea as 'Reporting area[area]',


Period,
last_year as 'Last year[last]',
this_year as 'This year[this]',
next_year as 'Next year[next]'
from mydb.ProductionSummary;

By defining the column 'Period' as a cross tabulation column, the distinct values in the column are calculated
as group columns and the data columns are calculated underneath each group column.

/*
Define the Period as a cross tabulation column and 'next' column to be the last data
column inside the cross tabulation.
*/
select 'dbr.crosstab', 'Period', 'next';
select 'dbr.sum', 'last', 'this', 'next';
select 'dbr.hsum', 'last', 'this', 'next';
select 'dbr.crosstab.title', 'Total H1';

122
Commands

select 'dbr.summary.text', 'area','Total';

select RepArea as 'Reporting area[area]',


Period,
last_year as 'Last year[last]',
this_year as 'This year[this]',
next_year as 'Next year[next]'
Optional
from mydb.ProductionSummary;

The 'no_null_data' option allows suppressing null crosstable column generated for example with LEFT JOIN.
The row is shown (if other rows contain data), but the NULL column will not be created as crosstab data column.

The example creates rows for each month even if the month has no given rate for the hotel. As crosstab column
'name' will create a NULL value due LEFT JOIN, the NULL column is suppressed with the 'no_null_data'-option.

create temporary table d (


d date
);

insert into d values ('2016-01-01'),('2016-01-02'),('2016-01-03');


select 'dbr.crosstab', 'name';
select 'dbr.crosstab.options', 'no_null_data';

select d.d as 'Day', h.name as '[name]', h.rate as ''


from d d
left join (
select cast('2016-01-02' as date) as d, 'The Imprerial' as name, 680 as 'rate'
from mydbr_version
) as h on h.d=d.d
order by d.d;

Header levels
Commands
dbr.hdr - Set header level in a query
dbr.hdr.options - Do not hide repeating headers

Syntax

select 'dbr.hdr', ColumnReference [, ColumnReference ...]


select 'dbr.hdr.options', 'option'

Header level options:

• show - Keep repeating headers visible. By default myDBR hides repeating headers

123
Commands

Explanation

With a header level you can group rows that have the same data under selected header columns as a single
entity. When specifying a header level, the repeating data is shown only once and any aggregate function applied
to the result set will be calculated as a subtotal for each header level. You can set more than one header level
by simply reissuing the dbr.hdr-command for each header level you want to assign.

In order for myDBR to do the header levels efficiently (minimal server load) it is required that the rows in result
set are sorted in the same order as the header levels are set.

Examples

We have our data set:

select SupplierName, Year, Quarter, sum(Items) as 'Items'


from mydb.exampledata e
group by SupplierName, Year, Quarter;

which brings out the following data:

By assigning a header level the to first column we get the following result:

select 'dbr.hdr', 'SupplierName';

select SupplierName, Year, Quarter, sum(Items) as 'Items'


from mydb.exampledata e
group by SupplierName, Year, Quarter;

124
Commands

However, in most cases the header level is combined with an aggregate function to be applied to the selected
header set. We'll use sum in next step:

select 'dbr.hdr', 'SupplierName';


select 'dbr.sum', 'Items';

select SupplierName, Year, Quarter, sum(Items) as 'Items'


from mydb.exampledata e
group by SupplierName, Year, Quarter;

As a result we see that the aggregate function sum is calculated for each header set with a total of all rows.
Note that the group by-clause will sort the data into the right order, so myDBR does not have to cache all the
data when processing the report.

125
Commands

Now if we add the Year-column as another header level to the report query we have following query:

select 'dbr.hdr', 'SupplierName';


select 'dbr.hdr', 'Year';
select 'dbr.sum', 'Items';

select SupplierName, Year, Quarter, sum(Items) as 'Items'


from mydb.exampledata e
group by SupplierName, Year, Quarter;

Now subtotals are calculated each time the header level break occurs on either level.

126
Commands

Appearance
Commands
dbr.accordion - Organize report elements with accordions
dbr.accordion.close - Marks the end of an accordion
dbr.accordion.class - Define your own accordion style with a class
dbr.accordion.style - Define your own accordion style
dbr.column.filter - Add a client side filter for a column
dbr.column.title - Define the title for a column in cases where the content of the column is dynamic
dbr.collapse - Collapse selected columns to make more compact view
dbr.colsort - Alias for dbr.sortcol
dbr.compare - Show database results side by side
dbr.compare.options - Change compapare behavior
dbr.divify - Use DIV's instead of tables in output
dbr.header.group - Add additional header row in order to group columns
dbr.keepwithnext - Makes next element to be placed side by side with the current one
dbr.lockcolumns - Lock leftmost columns when resultset does not fit into the screen
dbr.no_data - Define a placeholder for queries that do not return any data
dbr.nosort - Disable sorting on specified columns
dbr.parameters.show - Make parameter input visible in report

127
Commands

dbr.pageview - Show a row from the database in a page view


dbr.refresh - Make report automatically refresh itself at a given interval or just once if no parameters are given
dbr.resultset.options - Allows combining multiple result sets by skipping header/footer
dbr.rownum - myDBR replaces the command with the row number in the result set
dbr.rownum.set - Initialize the rownum-value
dbr.search - Disable/enable search & export for a given result set
dbr.scrollable - Make result set scrollable with fixed number of rows
dbr.sort - Set initial sorting order
dbr.sortcol - Sort a column based a value from another column
dbr.sortmethod - Override the default sort method
dbr.sortorder - Override the default initial sort order. The default is 'intelligent'
dbr.sort.remember - Remember user's sort order
dbr.header.tooltip - Define tooltip for the header
dbr.tooltip - Define cell's tooltip
dbr.pager - Attach the pager component to a table report
dbr.tab - Organize report elements with tabs
dbr.tab.class - Define your own tab style with class
dbr.tab.close - Mark the tab element as closed
dbr.tab.next - Switch to next unpopulated tab
dbr.tab.selected - Set's the default tab by name or by tab order number (0=first, 1=second)
dbr.tab.style - Define your own tab style

Syntax

select 'dbr.accordion', 'accordion name' [, 'jQuery accordion options']


select 'dbr.accordion.close'
select 'dbr.accordion.class', 'css_classname'
select 'dbr.accordion.style', 'css style definition'
select 'dbr.column.filter', ColumnReference[, 'select' | 'text']
select 'dbr.column.title', ColumnReference, title
select 'dbr.collapse', ColumnReference [,ColumnReference... ]
select 'dbr.colsort', ColumnReferenceTo, ColumnReferenceFrom
select 'dbr.compare'
select 'dbr.compare.options' [no_compare ColumnRef, ColumnRef... | compare_column
ColumnRef_Target, ColumnRef_Compare ]
select 'dbr.divify' [, 'css_classname']
select 'dbr.header.group', 'name', ColumnReferenceFrom, ColumnReferenceTo
select 'dbr.keepwithnext' [, pixels]
select 'dbr.lockcolumns', ColumnReferenceToLockTo [, 'fixedrow' ]
select 'dbr.no_data', 'message', 'css_classname'
select 'dbr.nosort', ColumnReference [,ColumnReference... ]
select 'dbr.parameters.show'
select 'dbr.pageview'
select 'dbr.refresh' [[,seconds], ['counter', ['no_toggle']]]
select 'dbr.resultset.options', 'skip_header_footer' | 'skip_header' | 'skip_footer'
select 'dbr.rownum', data from table
select 'dbr.rownum.set', value
select 'dbr.search', 1
select 'dbr.scrollable' [, number_of_rows_to_show ]
select 'dbr.sort', ColumnReference, 'asc' | 'desc'
select 'dbr.sortcol', ColumnReferenceTo, ColumnReferenceFrom
select 'dbr.sortmethod', ColumnReference, 'text' | 'number' | 'currency' | 'ipaddress' |
'url' | 'percent' | 'date' | 'time' | 'rownum'
select 'dbr.sortorder', ColumnReference, 'intelligent' | 'desc' | 'asc'
select 'dbr.sort.remember'
select 'dbr.header.tooltip', ColumnReferenceTo, 'Tooltip text'
select 'dbr.tooltip', ColumnReferenceTo, ColumnReferenceFrom
select 'dbr.pager' [, nbr of rows per page, [pager text] ]
select 'dbr.tab', 'tab name' [, ajax_call_for_content | myDBR report ]
select 'dbr.tab.class', 'css_classname'
select 'dbr.tab.close'

128
Commands

select 'dbr.tab.next'
select 'dbr.tab.selected', tab
select 'dbr.tab.style', 'css style definition'

Pageview
dbr.pageview

Explanation
The dbr.pageview-command is used to show one row in a record-style format.

Example
Select a single row as a result set:

select title, description, release_year, special_features, last_update


from mydb.film f
where film_id=1;

Result is a single row.

when we apply the dbr.pageview-command we get the result out in the following, more readable layout:

select 'dbr.pageview';

select title, description, release_year, special_features, last_update


from mydb.film f
where film_id=1;

Collapsible columns
dbr.collapse

Sometimes number of columns in the report can make the report too wide and difficult to read. With collapse
functionality you can hide some of the columns from initial display, but yet let user to show them by clicking
the row.

The functionality is much like the 'inline' linked report, just that in collapsible no linked report is required. The
'inline' linked report provides more flexibility on the layout.

129
Commands

select 'dbr.collapse', 'ID', 'Year', 'Date', 'Image';


select 'dbr.colstyle', 'Image', '[width:150px]image';

select
Title,
Description,
ID,
Year,
Date,
Image
from mydb.data;

Placing elements side by side


dbr.keepwithnext

Explanation
By default myDBR lays out the elements each on their own line. If you wish to place elements next to each
other use the dbr.keepwithnext-command. Optional parameters define the space around the elements. See
more information at See layouts for details.

Creating an automatic row number


dbr.rownum

Explanation
You can make myDBR to create automatic row numbers for you with dbr.rownum'-command. The following
report will produce output for two columns where the first column is a rownumber column.

select 'dbr.rownum' as 'Row number', title


from film;

Adding additional column header group


dbr.header.group

Explanation
Group normal query (not crosstab) columns with additional header row by using dbr.header.group-command

select 'dbr.header.group', 'Used', 'hours_used', 'cost_used';


select 'dbr.header.group', 'Budget', 'hours_budget', 'cost_budget';

130
Commands

select
phase as 'Phase',
hours_used as 'Hours[hours_used]',
cost_used as 'Cost[cost_used]',
hours_budget 'Hours[hours_budget]',
cost_budget as 'Cost[cost_budget]'
from mydb.data;

Set column sorting and override the default sorting method for a column

dbr.sort, dbr.sortmethod, dbr.colsort

Explanation

By default myDBR makes columns sortable. Users can sort the columns by clicking the header. myDBR offers
multilevel support and a variety of sorting methods. A sorting method understands the data and carries out an
intelligent sorting based on the data. The dbr.sort-command defines a column and a sorting order. If multiple
dbr.sort-commands are issued, a multilevel sort is performed.

Example

Set the predefined sorting order (ascending based on amount and ascending based on ip_address) and
make sure the first column which contains both ip_addresses and hostnames are sorted alphabetically. The
ip_address column is sorted based on the IP-address.

select 'dbr.sort', 'amount', 'desc';

select 'dbr.crosstab', 'Quarter';


select 'dbr.sum', 'amount';
select 'dbr.hsum', 'amount';
select 'dbr.hidecolumn', 'down'; // This is used for sorting

select 'dbr.sortmethod', 'Host', 'text';


select 'dbr.sort', 'amount', 'asc';
select 'dbr.sort', 'ip', 'asc';
select 'dbr.sortcol', 'Down since', 'down'; // Sort 'Down since'-column based on datetime
from column 'down'

select
status as 'Status',
host_ip as 'Host',
ip_address as 'IP Address[ip]',
ping,
date_format(down, '%D %b, %H:%i') as 'Down since',
down,
quarter as 'Quarter',
amount as '[amount]'
from mydb.mytable;

131
Commands

Disabling sorting on selected columns

dbr.nosort

Explanation

If you decide that a column or the result set as whole should not be sortable, you can disable the sorting on
selected or all columns. With no columns specified or the column number set to zero, 'dbr.nosort' disables
sorting altogether. If you have a very large result set, you can disable the sorting to speed up things as the
sorting is done via JavaScript in the browser and a large dataset with a slow machine / browser may slow the
report initialization.

Example

Disable the sorting on image column:

select 'dbr.nosort', 'Preview';

select 'Part 1' as 'Part name',


'WDC-2345-1' as 'Code',
'dbr.html:<img src="http://www.mysite.com/parts/WDC-2345-1.jpg">' as 'Preview'
union
select 'Part 2',
'WDC-2345-2',
'dbr.html:<img src="http://www.mysite.com/parts/WDC-2345-2.jpg">'
union
select 'Part 3',
'WDC-2345-3',
'dbr.html:<img src="http://www.mysite.com/parts/WDC-2345-3.jpg">';

Now user can sort columns 1 and 2, but sorting on column 3 is disabled:

132
Commands

Search / export visibility


dbr.search

Explanation

By default, myDBR's objects export and search/filter functionality is hidden behind a small triangle. You can
change this behavior by using dbr.search. If set to a value of 1 the export/filter area is shown by default. If
set to a value of 0, the ares is hidden altogether.

select 'dbr.search', 1;

Note that you can set the export and search/filter functionality to be on by default in userstyle.css by setting
div.search { display: block; }

Note
Note that you can set the search / export feature to be on by default by setting search = true in the
defaults

Auto refresh
dbr.refresh

Explanation

When used, the report will automatically refresh itself at given interval.

The first optional parameter for the command is 'seconds' after which the report is refreshed. When 'seconds'
is not provided, the refresh is done immediately. An immediate refresh is used for example when an editable
report returns the dbr.refresh-command after which the edited values in report will be displayed.

The second optional parameter is constant 'counter'. When applied, the calculated seconds will be shown in top
of the report and the user is able to pause the counter by clicking on it.

The third optional parameter is the constant 'no_toggle'. When applied, a counter will be visible, but the user
is not able to stop the counter.

select 'dbr.refresh', 5; /* Refresh after 5 seconds */

133
Commands

select 'dbr.refresh', 50, 'counter'; /* Refresh after 50 seconds. User can stop the
counter by clicking on it. */

select 'dbr.refresh', 50, 'counter', 'no_toggle'; /* Refresh after 50 seconds. User cannot
stop the counter. */

Set dynamic column title


dbr.column.title

Explanation

When a column contains dynamic data the column title can also be dynamic

if (in_Gross>0) then
select 'dbr.column.title', 'grossnet', 'Gross';
else
select 'dbr.column.title', 'grossnet', 'Net';
end if

select Name, if ( in_Gross>0, gross, net ) as '[grossnet]'


from mytable;

Show parameters within report


dbr.parameters.show

Explanation

By default myDBR allows parameters to be changed in a report if the user clicks the "Change report parameters"
button. The dbr.parameters.show'-command makes the values visible by default.

select 'dbr.parameters.show';

Use DIV's instead of tables


dbr.divify

Explanation

By default myDBR shows results as HTML tables. With dbr.divify-command you can use DIV's. This allows
more flexible formatting in CSS and post-processing in JavaScript.

An example query:

select 'dbr.divify', 'divifythis';


select 'dbr.hidecolumns', 'divrow';
select 'dbr.rowclass', 'divrow';

select name, population, code, 'divrow'


from countries;

This will produce the following HTML code:

134
Commands

<div class="divifythis">
<div class="divrow">
<div class="name">Maldives</div>
<div class="population">286 000</div>
<div class="code">MDV</div>
</div>
<div class="divrow">
<div class="name">Brunei</div>
<div class="population">328 000</div>
<div class="code">BRN</div>
</div>
</div>

Paging result sets


dbr.pager

myDBR offers a client side pager for browsing larger result sets.

With the pager you can embed larger table elements into the report and still control the size of the element.
It will display a pager component on top of the result set. With this the tser is able to navigate the result set
using the pager.

Example

select 'dbr.colstyle', 'release', '%d'; // Formatting the year -> will not use the
thousand separator

select 'dbr.pager', 5;

select title as 'Title',


release_year as 'Release Year[release]',
rental_rate as 'Rental Rate',
length as 'Length'
from film;

Note
The pager component is a client side component, so it is intended to be used in cases where the size
of the result set is manageable in the client. For very large result sets consider limiting the number of
rows or use linked reports. (Users are seldom able to handle very large sets anyway).

Using tabs to organize your report content


dbr.tab, dbr.tab.next, dbr.tab.style, dbr.tab.class

135
Commands

You can create tabs in your report to break content into multiple sections that can be swapped to save space.
The content of the tab can either consist of static report elements or the content can be fetched using Ajax
when the tab is clicked.

To use tabs, you first declare each tab with the dbr.tab-command. The first parameter for the dbr.tab is the
tab's name. The second optional parameter is an URL for Ajax call or a myDBR report name (with parameters)
to be called when the tab is clicked. If no second parameters are given, the content of the tab is expected to
come later in the report.

Once the tabs are declared, the content of the tab needs to be provided. For each non Ajax/myDBR report
tab, the content needs to be defined. Once the content of the tab is defined, next tab is selected with the
dbr.tab.next-command. The dbr.tab.next-command selects the next tab which has not been Ajax URL
or myDBR report defined.

If you wish to define your own styles for a tab, the commands dbr.tab.style and dbr.tab.class can be
used. The most common use case for styles is that the tab width is be set to fixed width while the content width
between tabs varies.

Example

/* Declare the tabs. Second tab is fetched via ajax when user clicks the tab. In case of
myDBR report add &embed=1 to the end of the URL */

select 'dbr.tab', 'First tab';


select 'dbr.tab', 'myDBR report tab', 'sp_DBR_linked_report', v_param_1;
select 'dbr.tab', 'Ajax tab', 'report.php?
r=548&m=1&h=55589f83ec7daa84432118425499bd5875f6d6fa&embedi=1';
select 'dbr.tab', 'Fourth tab';

/* Now the tabs are declared, so the content of 'First tab' is populated */

select 'dbr.title', 'First tab title';

select ID, Title, release_year as 'Year'


from film;

/* dbr.tab.next moves to next unpopulated tab which is the 'Fourth tab' */


select 'dbr.tab.next';

call sp_DBR_another_report( inMyParam );

select 'dbr.tab.close';

136
Commands

Using accordions to organize your report content

dbr.accordion, dbr.accordion.close, dbr.accordion.style, dbr.accordion.class

An accordion is a UI element (much like a horizontal tab), which is best suited for displaying a limited number
of items.

To use an accordion start a new accordion with the dbr.accordion-command. Each subsequent
dbr.accordion-command adds a new accordion element to the existing one. The content of each
accordion comes after the 'dbr.accordion'-command. Once finished with the accordion close the element with
dbr.accordion.close-command.

You can customize the accordion behavior by passing the jQuery accordion options as second parameter to
the dbr.accordion-command. The 'active' -option defines the default open section (starting from zero). To
have all accordion sections 'closed' by default, you can use 'active:false', option. To enable multiple accordion
sections to be open at same time, you can use the 'multiopen:true' option . When defining multiple options, you
can separate them with comma: 'active:false,multiopen:true'.

You can modify the default accordion style with 'dbr.accordion.style' and 'dbr.accordion.class'. The former takes
a CSS style as parameter and the second a CSS class. Any definition made here is added to the accordion
wrapper div.

Example

select 'dbr.text', "Before accordion", 'comment';

select 'dbr.accordion.style', 'width:700px';

select 'dbr.accordion', 'First accordion';

select 'dbr.text', "This is part of 'First accordion'-content", 'comment';

/* Some other content for first accordion */

select 'dbr.accordion', 'Second accordion';

call sp_DBR_accordion_2_content();

select 'dbr.accordion', 'Third accordion';

select ID, Title


from mydb.film;

select 'dbr.accordion.close';

select 'dbr.text', "After accordion", 'comment';

137
Commands

Placeholder for nonexistent data


dbr.no_data

You can define a placeholder for queries that return no data. The default behavior is that myDBR outputs
the query header without any rows and in case of a chart it will create a placeholder chart element. With the
dbr.no_data-command you can display your own message instead.

If no css-class is given, myDBR uses the default 'div.no_data'-style. You can define your own by adding it as
a second parameter.

Example

select 'dbr.no_data', "No films were found", 'comment';

select ID, Title


from mydb.film
where film_creation>'2020-01-01';

Sticky headers
By default myDBR uses sticky headers where report table element headers stay on screen when the user scrolls
the document. You can disable this by adding the class 'fixedheader' to the result set.

Lock leftmost columns


dbr.lockcolumns

When you have a wide resultset and you scroll to the right, you can lock the leftmost columns to be always
visible. dbr.lockcolumns-command's first parameter defines the last column to be locked. The optional second
parameter 'fixedrow' keeps row height constant and can be used when data in a cell spans multiple rows.

138
Commands

Example

select 'dbr.lockcolumns', 'title';

select
title,
description,
release_year
from film f;

Using column filters


dbr.columnfilter

Column filters allow filtering rows based on columns data. A column filter can be either a select list or a text field.

Example

select 'dbr.column.filter', 'Category', 'select';


select 'dbr.column.filter', 'Title', 'text';

select
g.name as 'Category',
title as 'Title'
from film f
join film_category fg on f.film_id=fg.film_id
join category g on g.category_id =fg.category_id;

Resultset options
dbr.resultset.options

139
Commands

With resultset options you can combine multiple result sets into one table. Resultset can be a result of a query
or a template that you insert into the report element.

Example

select 'dbr.column.filter', 'Category', 'select';


select 'dbr.column.filter', 'Title', 'text';

select
g.name as 'Category',
title as 'Title'
from film f
join film_category fg on f.film_id=fg.film_id
join category g on g.category_id =fg.category_id;

Compare
dbr.compare

With dbr.compare you can display result set rows side-by-side and optionally format the minimum / maximum
and equal values from different rows.

By default, a CSS class (compare_min, compare_max, compare_same) is applied to each cell. You can choose
not to compare a column by using dbr.compare.options, 'no_compare', 'columnRef. Additionally, you can choose
the column which is used for compare for a selected column: select 'dbr.compare.options', 'compare_column',
'ColumnRef_Target', 'ColumnRef_Compare';

Example

select 'dbr.css', '.compare_min {background: green; color:white;}';


select 'dbr.css', '.compare_max {background: red; color:white}';
select 'dbr.css', '.compare_same {background: #d0edfe;}';

select 'dbr.colstyle', 'Description', '[width:200px]';


select 'dbr.colstyle', 'Release year', '%d';

select 'dbr.compare';

-- Do not compare Title and film_id columns


select 'dbr.compare.options', 'no_compare', 'Title', 'film_id';

-- Compare Description-column based on film_id


select 'dbr.compare.options', 'compare_column', 'Description', 'film_id';

140
Commands

select
f.title as 'Title',
f.description as 'Description',
f.release_year as 'Release year',
f.rental_rate as 'Rental rate',
f.length as 'Length',
f.film_id
from demo.film f
where f.film_id in (1, 3, 8);

Charts
Commands
dbr.chart - Create a chart from the following result set
dbr.chart.options - Assign special options for the chart
dbr.chart.color - Define own colors

Syntax

select 'dbr.chart', chart_type, [ chart_name [, xSize, ySize ] ]


select 'dbr.chart.options', option [, value]
select 'dbr.chart.color', hex ARGB color [, hex ARGB color]

Explanation
myDBR allows you to create charts based on the result set. myDBR supports multiple charting modules with
distinct capabilities:

• FusionCharts Free (from InfoSoft Global) offers Flash-chart capabilities. This module comes with myDBR as
a free chart package.

• ChartDirector (from Advanced Software Engineering) offers true picture based charting with advanced
options. ChartDirector is a commercial product requiring a license. The benefit of using ChartDirector over
FusionCharts is that the charts are generated as a picture (PNG) instead of relying on the client-side Flash-
plugin. Better support for printing is also a benefit of ChartDirector-based charts.

• With Graphviz support myDBR is able to draw complex network and hierarchal reports. The charts generated
with Graphviz-module can also output the source code for the chart to be processed with external charting
applications supporting Graphviz's underlying charting language.

Charts can be divided into four categories:

141
Commands

• XY-charts (XY), where the data set consist of X-value (category) and Y-value (data).

• Multi series-charts (MS), where the data set consist of X-value (category) and multiple data values (Y's).

• Meter-chart (Meter), where the data set consist of a single meter value.

• Network-charts (Network), where the data set consist of parent-child / node-node pairs.

• Other charts

Chart types:

Chart type Command Type Example Flash Image Graphviz


Charts Charts
Column Column XY Yes Yes

3D Column Column3d XY Yes Yes

Multi-Series MSColumn MS Yes Yes


column

3D Multi-Series MSColumn3D MS Yes Yes


column

Stacked StackedColumn MS Yes Yes


Column

3D Stacked StackedColumn3DMS Yes Yes


Column

142
Commands

Chart type Command Type Example Flash Image Graphviz


Charts Charts
Stacked Bar StackedBar MS Yes Yes

3D Stacked StackedBar3D MS Yes


Bar

Stacked Area StackedArea MS Yes Yes

3D Stacked StackedArea3D MS Yes


Area

Line Line XY Yes Yes

3D line Line3D XY Yes

Multi-Series MSLine MS Yes Yes


Line

143
Commands

Chart type Command Type Example Flash Image Graphviz


Charts Charts
Multi-Series MSLineDY MS Yes
Line Double Y

Multi-Series MSLineDY3D MS Yes


Line Double Y
3D

Spline Spline XY Yes

Multi-Series MSSpline MS Yes


Spline

Stepline Stepline XY Yes

Multi-Series MSStepline MS Yes


Stepline

Pie Pie XY Yes Yes

144
Commands

Chart type Command Type Example Flash Image Graphviz


Charts Charts
3D Pie Pie3D XY Yes Yes

Bar Bar XY Yes Yes

3D Bar Bar3D XY Yes

Multi-Series MSBar MS Yes Yes


Bar

Area Area XY Yes Yes

3D Area Area3D XY Yes

Bubble Bubble XY Yes

145
Commands

Chart type Command Type Example Flash Image Graphviz


Charts Charts
3D Bubble Bubble3D XY Yes

Multi-Series MSArea MS Yes Yes


Area

Percent Percentcolumn MS Yes


Column

Percent Bar Percentbar MS Yes

Percent Area Percentarea MS Yes

Donut Donut (or XY Yes Yes


Doughnut)

3D Donut Donut3D (or XY Yes


Doughnut3D)

146
Commands

Chart type Command Type Example Flash Image Graphviz


Charts Charts
Scatter Scatter XY Yes

Pyramid Pyramid XY Yes

Pyramid 3D Pyramid3D XY Yes

Cone Cone XY Yes

Cone 3D Cone3D XY Yes

Funnel Funnel XY Yes

Funnel 3D Funnel3D XY Yes

147
Commands

Chart type Command Type Example Flash Image Graphviz


Charts Charts
Multi-Series MSColumnDY MS Yes
Column Double
Y

Multi-Series MSColumnDY3D MS Yes


Column Double
Y 3D

Multi-Series MSColumnLineDYMS Yes Yes


Column Line
Double Y

Multi-Series MSColumnLineDY3D
MS Yes Yes
Column Line
Double Y 3D

Multi-Series MSColumnSplineDY
MS Yes
Column Spline
Double Y

Multi-Series MSColumnSplineDY3D
MS Yes
Column Spline
Double Y 3D

148
Commands

Chart type Command Type Example Flash Image Graphviz


Charts Charts
Meter Meter Meter Yes

Linear meter Linearmeter Meter Yes

Semicircle Semicircle Meter Yes

Rectangular RectangularmeterMeter Yes


meter

Donut Percent Donutpercent Meter Yes


(or
Doughnutpercent)

Hierarchy Hierarchy Network Yes

149
Commands

Chart type Command Type Example Flash Image Graphviz


Charts Charts
Network Network Network Yes

Gantt Gantt Gantt Yes

Polar Area PolarArea MS Yes

Polar Line PolarLine MS Yes

Polar Spline PolarSpline MS Yes

Polar Spline PolarSplineArea MS Yes


Area

Polar Scatter PolarScatter MS Yes

150
Commands

Chart type Command Type Example Flash Image Graphviz


Charts Charts
Radar Area RadarArea MS Yes

Radar Line RadarLine MS Yes

Radar Spline RadarSpline MS Yes

Radar Spline RadarSplineArea MS Yes


Area

Boxwhisker Boxwhisker Other Yes

Floatingbox Floatingbox Other Yes

Scatter3D Scatter3D Other Yes

151
Commands

Chart type Command Type Example Flash Image Graphviz


Charts Charts
MSScatter3D MSScatter3D Other Yes

How to create a chart?

To create a chart, you need to select the chart type and then fetch the appropriate data for the chart. Here is
a an example of a sample pie chart generation.

select 'dbr.chart', 'Pie', 'Sample Pie chart';

select category, total_sales


from mydb.sales_by_film_category;

Selecting data for the chart

Depending on the chart type selected, the data must be selected accordingly:

XY chart

For XY-charts, use the following data selection:

select X, Y
from mydb.Data;

Multi series chart

For multi series charts (MS), use the following data selection:

select Category (x), Series (label), Value (y)


from mydb.Data;

Scatter chart

For a scatter chart, use the following data selection:

select Series, x, y
from mydb.Data;

Boxwhisker chart

For a boxwhisker chart, use the following data selection:

select Series, bottom, top, [min, [max, [middle]]]

152
Commands

from mydb.Data;

Scatter3D chart

For a Scatter3D chart, use the following data selection:

select select x, y, z
from mydb.Data;

MSScatter3D chart

For a MSScatter3D chart, use the following data selection:

select select Series, x, y, z


from mydb.Data;

Meter chart

For meter charts, simply select the data value.

select 'dbr.chart', 'meter';

select 78;

Network chart

For network charts there are two options:

Option 1 where the chart is drawn based on single values / node.

select node1, node2 [, edge_style]


from mydb.Data;

Option 2 where node contains both an ID value and the visible value to the user. This can used when making
charts to be exported and you want to keep the ID's.

select node1_id, node2_id, node1_name, node2_name [, edge_style]


from mydb.Data;

Network charts are generated using Graphviz technology and Graphviz formatting can be applied to the charts
using the 'dbr.chart.options'-command. Option can be separately set to nodes (is a parent) and leaves (is only a
child). The options are set as a comma separated list and can contain all the formatting supported by Graphviz.

select 'dbr.chart.gv.style', 'node', 'shape=house,fillcolor=#CCCCFF,style=filled';

Gantt chart

Gantt chart has a label, starttime and endtime and optional category

153
Commands

select 'dbr.chart', 'gantt';

select label, starttime, endtime [, category]


from data;

Setting own chart colors

Commands

dbr.chart.color - Set chart colors

Syntax

select 'dbr.chart.color', hex ARGB color, [, hex ARGB color]

Default colors are defined in the defaults.php-file. If you wish to change the default colors, you can edit the
file to contain your colors. Alternatively you can use the 'dbr.chart.color'-command to override the default colors.
If you wish to override the default colors and use the same definition in multiple reports, the easiest way to do
this is to place the command in a separate stored procedure and call the procedure from your report.

We'll first define the procedure containing the colors (you can call 'dbr.chart.color' multiple times):

create procedure sp_ADBR_MyColors()


begin

select 'dbr.chart.color', '0x300000cc', '0x4066aaee', '0x40ffbb00', '0x40ee6622';

end

And then use it in a report:

call sp_ADBR_MyColors();
select 'dbr.chart', 'Cone3d', 'Cone3d';

select 'Funds', 156


union
select 'Bonds', 123
union
select 'Stocks', 211
union
select 'Cash', 179;

And the chart will use the colors you defined:

154
Commands

Chart options
With chart options you can affect the chart's visual appearance. In case of flash- and image-based charts,
myDBR offers the most common options as standardized commands making the shift from one chart module
to another easy. In addition to the common options, myDBR allows passing native commands to each chart
module for additional formatting. With access to native commands you are able to access individual features of
each chart module without myDBR acting as a gatekeeper.

Common chart options

Commands
dbr.chart.options - Specify chart options
dbr.chart.gv.option - Specify GraphViz chart options

Syntax

select 'dbr.chart.options', option {, value{, value}}


select 'dbr.chart.gv.option', option

Image and Flash chart options:

• chart_transpose - converts Category and Series in multi series charts

• axis, x [, y [, y2]] - sets x and y axis name as defined in parameter (select 'dbr.chart.options','axis', 'x-axis',
'y-axis', 'y-axis2')

• imagechart - makes myDBR use ChartDirector PNG-based charts

• flashchart - makes myDBR use FusionCharts Flash-based charts

• showvalues, 0 | 1 | 'data' | 'total' | 'percent' - shows (1) or hides (0) values in a chart. 'data' shows values in
indivudual data points, 'total' shows values in aggregate, 'percent' shows percentage instead of the value

155
Commands

• alternatecolor, color1, color2 - set's chart canvas colors ( color1 and color2 )

• scale, min, max - set's y-axis min and max values (select 'dbr.chart.options', 'scale', 300, 700)

• scale2, min, max - set's 2nd y-axis min and max values (select 'dbr.chart.options', 'scale', 300, 700)

• scale_x, min, max - set's x-axis min and max values (select 'dbr.chart.options', 'scale_x', 0, 100)

• rotateNames, degree - rotates the x-axis names to the degree specified (free rotate for image chart, flash
charts only rotates 90 degrees)

• numberSuffix, 'suffix' - sets visible suffix for values (use dbr.colstyle for image charts)

• showLegend, 0 - hides legend from multi series chart

Image chart / Graphviz only:

• font [,font] [,font_size] - Set chart font/font size for all chart elements (axis, title, lables etc) all at once

• shading, shading_value - Pie chart shading value (LocalGradientShading, GlobalGradientShading,


ConcaveShading, RoundedEdgeShading, RadialShading, FlatShading and RingShading). See more info
from ChartDirector documentation.

• marker series, [marker, [size, [edge_color]]] - Specify a marker type and size used in chart (scatter/line). If
the marker_series is null same marker type is used in all series.

• format, imageformat - Defines the image format (PNG, SVG, GIF, JPG, WMP, BMP, SVGZ)

• 3d, depth - Defines 3D depth in pixels (-1=auto, 0=2D, >1 depth in pixels)

• autoscale_x [ topExtension [, bottomExtension [, zeroAffinity ]]] - Autoscale the chart x-axis to see differences
better

• autoscale_y [ topExtension [, bottomExtension [, zeroAffinity ]]] - Autoscale the chart y-axis to see differences
better

• chart.scale scale_percentage - Scale the chart to given percentage of the screen. SVG-charts scale best.

• datetimescale, 1 [, lower_limit, upper_limit [, major_tick_inc, [minor_tick_inc]]] - Treats first column as a


datetime and uses datetime scaling on X-axis, optionally setting scaling, major and minor ticks. The lower_limit
and upper_limit are datetimes or times and major_tick_inc and minor_tick_inc are seconds.

• timevalue, 1 - Converts the seconds the in data column to a time value allowing times >24h to be displayed
in the chart

• cartesian - use cartesian coordinate system in the chart

• axis_noscale 1/0 - Do not sync x- and y-axis on cartesian charts

• numberscale - keep x-axis number scale the same

• background_color, color - Set chart background color

• edge_color, color - Set chart's edge color

• plot_edge_color, color - Set plot's edge color

• grid_color_horizontal, color - Set chart's horizontal grid color

• grid_color_vertical, color - Set chart's vertical grid color

156
Commands

• raised_effect, raised - Set edge raise in pixels

• title_font, font - Set title font

• title_font_size, size - Set title font size

• title_color, color - Set title color

• axis_font, font - Set axis font

• axis_font_size, size - Set axis font size

• axis_color, color - Set axis color

• fix_y_axis, 1 - Set y-axis alignment to right to fix SVG chart text spacing when font spacing is not correct
in ChartDirector

• x_axis_max_width, width - Set maximum length of x axis in a XY-chart

• y_axis_max_width, width - Set maximum length of x axis in a XY-chart

• z_axis_max_width, width - Set maximum length of x axis in a XY-chart

• x2_axis.show, 1 - Show the second x-axis

• x_axis_margin, margin - Add extra margin at the ends of the x-axis

• x2_axis_margin, margin - Add extra margin at the ends of the second x-axis

• x_axis_color, color - Set x-axis color

• y_axis_color, color - Set y-axis color

• x2_axis_color, color - Set x2-axis color

• y_axis_color, color - Set y-axis color

• z_axis_color, color - Set z-axis color

• y2_axis_color, color - Set y2-axis font color

• x_axis_font_color, color - Set x-axis font color

• y_axis_font_color, color - Set y-axis font color

• x2_axis_font_color, color - Set x2-axis font color

• y_axis_font_color, color - Set y-axis color

• y2_axis_font_color, color - Set y2-axis color

• z_axis_font_color, color - Set z-axis color

• y_axis_label_style, colstyle - Set style for y-axis labels

• y2_axis_label_style, colstyle - Set style for y2-axis labels

• x_axis_tick_middle, 1 | 0 - Define if tick-marks are placed in middle of title in x-axis

• padding_top, padding - Set top padding in pixels

• padding_left, padding - Set left padding in pixels

157
Commands

• padding_bottom, padding - Set bottom padding in pixels

• padding_right, padding - Set right padding in pixels

• title.align, 'left' | 'chart' - Align chart title to left of chart / middle of chart instead of the default middle of plot area

• hide 'all | ('bg', 'yaxis', 'xaxis', 'grid') - Hide parts of the chart: all (show just the chart, bg=plot area background,
x-axis, y-axis, grid)

• radius, radius - Set pie/funnel radius in pixels

• label_font, font - Set label font

• label_font_size, size - Set label font size

• label_font_color, color - Set label color

• legend.columns, column_nbr - Sets number of legends to use

• legend_font, font - Set legend font

• legend_font_size, size - Set legend font size

• legend_color, color - Set legend color

• legend.position, 'left' | 'right | 'top' | 'bottom' - Set legend position

• legend.style, 'background_color', 'edge_color', 'rounded_border[TL]', ['rounded_borderTR',


'rounded_borderBR', 'rounded_borderBL'] - Set legend style

• legend_reverse, 1 - Reverse the legend order

• line_width, width [, label] - Line width in line chart. Optionally selecting the label

• line.style[ series_name,] 'dash' | 'dot' | 'dotdash' | 'altdash' - Line style. series_name is required in multiseries
chart.

• bargap, 0..1 - Controls the gap between columns. Value is percentage <=1 (negative value overlaps).

• subbargap, 0..1 - Controls the gap between individual columns in multiseries column chart. Value is
percentage <=1 (negative value overlaps).

• width_per_item, width - When chart width is set to 'auto', this option determines the width for each item

• height_per_item, width - When chart height is set to 'auto', this option determines the height_per_item for
each item

• export_as_png, 1/0 - When doing export on svg chart, the option will determine if the chart is drawn as png
(some wkhtmltopddf versions may render some charts poorly). Global option in defaults.php exists for this.

• softlightning, 1/0 - Determines if softlightning is used on charts.

• series, 'series1' [, 'series2' [, 'series3'..,]] - Defines the series order in multiseries chart

• category_order, 'category1' [, 'category2' [, 'category3'..,]] - Defines the category display order in multiseries
charts.

• category_sort, 'string', 'numeric' | 'natural' - Set category display sorting order

• mark, value, color, width, [, 'text' [, text_angle]] - Add a mark line to a XY-chart

158
Commands

• target, color, width in px, height (0-1) - Add a target mark for bar and column charts (3rd data column)

• series_axis, series_name, 1 | 2 - Choose the axis for the series in double Y-axis charts.

• InnerRing, size - Meter-chart inner ring proportional size

• OuterRing, size - Meter-chart outer ring proportional size

• skip_null_values, 0 - By default NULL values in charts are treated as missing values. If this option is turned
on, they are treated as zeros

• allow_gaps, 1 - If the options is turned on, missing values (or values containing NULL) are drawn into a line
chart allowing gaps to appear to the line(s). This option turns the markers in the line on by default in order to
show values that appear between two missing values. See 'marker'-option how to specify the marker.

• tooltip, '[ColumnReference] [ColumnReference]' - Define the mouse tooltip content with the ability to refer
to data columns

• tooltip_animate, 1/0 - Allows disabling tooltip animation

• xy_plot_fill, 1/0 - Use full chart area for the plot area and hide axis

• trendline, line_color[, title, line_width [, SeriesName], [regrssion_type [,regression_degree]]] - Adds a


trendline to the chart (line, column, bar)

• label_color, label, color - Allows you to define a color based on a label name (XY-charts) or based on the
series name (multi series charts)

• gantt.scale, days - Scale of the chart. Use 30 for month

• gantt.start, date - If specified, marks the start date for chart. If not, first date in data is used

• gantt.end, date - If specified, marks the end date for a chart. If not, the last date in data is used

• gantt.baseline, label, start, end - Sets the baseline for a label

• gantt.baseline_text, text - Baseline text, if not specified 'Baseline' is used if baselines are defined

• gantt.baseline_pattern.border, color - Baseline marker's border color

• gantt.baseline_pattern.color, color - Baseline marker's background color

• gantt.baseline_pattern.width, px - Baseline marker's width

• gantt.baseline_pattern.height, px - Baseline marker's height

• gantt.dateline, day - Extra date line

• gantt.label.height, px - Height of the gantt labels

• gantt.single_label, 1 - Use just one row / label

• gantt.start_of_day_format, chartdirector_date_format - ChartDirector date format for day gantt

• gantt.start_of_hour_format, chartdirector_time_format - ChartDirector time format for hour gantt

• gantt.start_of_month_format, chartdirector_date_format - ChartDirector date format for day gantt when


month changes

• scale, minimum, maximum, step - Y-Axis scale, If 'auto', scales x and y-axis equally in bubble-chart

159
Commands

• scale2, minimum, maximum, step - 2nd Y-Axis scale

• equal_scale_dy, 1/0 - Control scaling of Y-axis on DoubleY charts

• bubble.scale, 'x'|'y'|'pixel' - Individual bubble size relative to y-axis, x-axis or pixels.

• bubble.transparency, 30 - Bubble transparency to show overlapping bubbles

• meter.text, text - Optional text shown in a meter-chart.

• meter.text.font, font - Text font (default is arial)

• meter.text.size, size - Text size (default is 8)

• meter.text.color, color - Text color (default is black)

• linearmeter.orientation, 'horizontal'|'vertical' - Linearmeter orientation. Default is horizontal.

• linearmeter.zone, from, to, color - By default the zones are 0-33 green, 33-66 yellow and 66-100 red. With
this option you can define your own zones.

• linearmeter.height, height - Linearmeter height in pixels, default is 20 pixels.

• linearmeter.width, width - Same as linearmeter height

• linearmeter.text, text - Optional text shown in linearmeter.

• linearmeter.text.font, font - Text font (default is arial)

• linearmeter.text.size, size - Text size (default is 8)

• linearmeter.text.color, color - Text color (default is black)

• linearmeter.pointer.color, color - Pointer color

• meter.theme, theme - Select the meter theme ('black', 'white', 'default')

• meter.title.font, font - Set meter title font

• meter.title.size, size - Set meter title font size

• meter.title.color, color - Set meter title font color ('0xFF0000')

• meter.text, text - Set the meter text

• meter.text.font, font - Set meter text font

• meter.text.size, size - Set meter text font size

• meter.text.color, color - Set meter text font color ('0xFF0000')

• meter.label.font, font - Set meter label font

• meter.label.size, size - Set meter label font size

• meter.label.color, color - Set meter label font color ('0xFF0000')

• meter.pointer.color, color - Set meter pointer color ('0xFF0000')

• meter.color.type, 'step' | 'gradient' - Select if the meter colors are individual (steps) or gradient (the default)

• meter.color.step, step, color - Define step colors

160
Commands

• meter.color.gradient, step, color - Define gradient colors

• polar.grid, axis_color, axis_width, polar_color, polar_width, - Define chart colors for polarscatter-chart

• zone, from_value, to_value - Set background color for zones, range of values

• donut.size size - Donut thickness

• donutpercent.orientation 1/-1 - DonutPercent chart orientation. 1=clockwise, -1 anticlockwise

• donutpercent.size size - Donut thickness

• donutpercent.text text - Text inside the donut

• donutpercent.font font - Font for the text inside the donut

• donutpercent.font.size size - Font size for the text inside the donut

• donutpercent.font.color color - Font color for the text inside the donut

• scatter3d.x_axis_labels label - Replace x-axis numbers with a text label

• scatter3d.y_axis_labels label - Replace y-axis numbers with a text label

• scatter3d.z_axis_labels label - Replace z-axis numbers with a text label

• scatter3d.drop_line Series | null, color | null, 'dash' | 'dot' | 'dotdash' | 'altdash' - Define marker and the drop
line type for the data point

• scatter3d.plot_area center_x, center_y, xwidth, ydepth, zheight - Manually define the plot area

• scatter3d.view_angle elevation, rotation - Set orientation of the chart in degrees

• scatter3d.wall_color xy_color, yz_color, zx_color, border_color - Define charts wall colors

• scatter3d.z-legend 1 - Use single gradient legend for MSScatter3d chart instead of separate series legends

Where:

topExtension The top portion of the axis that no data point should fall into. For example, a value
of 0.1 means no data value will fall within the top 20% of the axis. The topExtension
must be between 0 to 1. Default is 0.1.

bottomExtension The bottom portion of the axis that no data point should fall into. For example, a
value of 0.1 means no data value will fall within the bottom 20% of the axis. The
bottomExtension must be between 0 to 1.

zeroAffinity ChartDirector will determine that it is "unreasonable" to use 0 as the axis starting point
if the data fluctuation (the difference between the maximum and minimum data values)
is too small compared with the data value. ChartDirector tests the "too small" condition
using the formula: maxDataValue * zeroAffinity < minDataValue. The default value is
0.5

regrssion_type Sets the regression type to be used. Available regression types are: LinearRegression
(default), ExponentialRegression, ExponentialRegression, LogarithmicRegression or
PolynomialRegression. In case of PolynomialRegression one must define the
regression_degree

regression_degree PolynomialRegression's degree.

Donut vs Doughnut For compatibility reasons you can use both 'donut.*' or 'doughnut.*' syntaxes.

161
Commands

GraphViz options

• diagram - pass diagram level parameters on to the chart (see example).

• node 'format in comma separated list' - sets node characteristics as Graphviz commands in Network chart

• chart_scale, 1 - Adds a UI element where user can scale Graphviz charts

FusionCharts options
For FusionCharts charts, myDBR passes any native <graph>-level formatting FusionCharts command directly
to FusionCharts, so you can use any of the module's formatting. The full list of options is available in
FusionChart's documentation under the "Chart XML Reference"-section.

select 'dbr.chart', 'Line';


select 'dbr.chart.options', 'bgColor', '0xDDDDDD'; // Gray background color
select 'dbr.chart.options', 'axis', 'X-axis', 'Y-axis'; // x-axis name
select 'dbr.chart.options', 'yAxisMinValue', 8; // minimum value for y
select 'dbr.chart.options', 'yAxisMaxValue', 22; // maximum value for y
select 'dbr.chart.options', 'showAnchors', 0; // do not show the anchors

select x, y
from mydb.mydata;

Image chart options


Formatting labels

Image chart's labels can be formatted using normal 'dbr.colstyle' command (CSS is not supported). 'dbr.colstyle'
also accepts ChartDirector's parameter substitution and formatting and ChartDirector Mark Up Language with
dbr.colstyle. The style string can contain:

1. printf-format for the value

2. Any free text

162
Commands

3. ColumnReferences to get value from another column

4. ChartDirector's Parameter Substitution Strings and Mark Up Language

In the example, the style string has a column reference ('[name]'), a value printf ('%.2f') and a ChartDirector's
parameter substitution string ({percent|0}).

select 'dbr.chart', 'pie';


select 'dbr.colstyle', 'value', '[name]: US$ %.2fK ({percent|0}%)';

select 'First' as 'name', 1.1 as 'value'


union
select 'Second', 2.2
union
select 'Third', 3.3;

Multiple options

The example show multiple options to be applied to the chart

declare v_s varchar(80);


declare v_w varchar(80);
declare v_color1 varchar(10);
declare v_color2 varchar(10);

set v_s = 'Sociology Doctorates Awarded (US)';


set v_w = 'Worldwide non-commercial space launches';

set v_color1 = '0xA9001D';


set v_color2 = '0x000000';

select 'dbr.title', '';


select 'dbr.chart', 'mssplineDY', concat('<*size=16,color=A9001D*>', v_w,
'\n<*color=AAAAAA*>correlates with\n<*color=000000*>', v_s), 1200, 500;
select 'dbr.chart.options', 'font', 12;

select 'dbr.chart.options', 'scale', 30, 60, 10;


select 'dbr.chart.options', 'scale2', 500, 700, 100;
select 'dbr.chart.options', 'rotateNames', 45;

163
Commands

select 'dbr.chart.color', v_color1, v_color2;


select 'dbr.chart.options', 'marker', v_w, 'DiamondShape', 12, v_color1;
select 'dbr.chart.options', 'marker', v_s, 'CircleShape', 12, v_color2;
select 'dbr.chart.options', 'x2_axis.show', 1;

select 'dbr.chart.options', 'x_axis_margin', 20;


select 'dbr.chart.options', 'x2_axis_margin', 20;

select 'dbr.chart.options', 'y_axis_font_color', v_color1;


select 'dbr.chart.options', 'x2_axis_font_color', v_color1;

select 'dbr.chart.options', 'y_axis_label_style', '%d Launches';


select 'dbr.chart.options', 'y2_axis_label_style', '%d Degrees Awarded';

select 'dbr.chart.options', 'axis', '', v_w, v_s;

select 'dbr.chart.options', 'legend', 1;


select 'dbr.chart.options', 'legend.position', 'bottom';
select 'dbr.chart.options', 'legend.columns', 1;

select 'dbr.chart.options', 'tooltip', '[sw]: [v]';

select y, sw, v
from mydb.mydata;

ChartDirector native options

ChartDirector offers variety of options for chart formatting. ChartDirector is implemented using PHP class
directives, and for native commands, myDBR offers direct access to the myDBR's ChartDirector's chart-object
($c), to the layer-object ($layer) and to trend layers array ($trend_layers). Commands are passed as PHP-code
snippets using 'dbr.chart.options', 'chartdirector'-command.

select 'dbr.chart.options', 'chartdirector', '$c->chartdirectorcommand';

In the example we'll change the y-axisto logarithmic and set minimum and maximum values, display only every
second x-axis label, set the border and background to gray and finally display a drop shadow for the chart.

select 'dbr.chart', 'Line', 'Chart';

select 'dbr.chart.options','rotateNames', 90;


select 'dbr.chart.options','showvalues', 0;

164
Commands

select 'dbr.chart.options','chartdirector', '$c->yAxis->setLogScale(300,700);$c->xAxis-


>setLabelStep(2);';
select 'dbr.chart.options','chartdirector', '$c->setBorder(0xEEEEEE);$c-
>setBackground(0xeeeeee);$c->setDropShadow();';

select Name, sum(Items)


from mydb.TestTable
where year(InsertDate)=2008
group by Name;

For full description of ChartDirector's class library, see the ChartDirector documentation.

If you have multiple charts and wish to keep same colors between different charts you can define colors based
on labels (or series). If you use the same color for the same labels in many places, it is easier to create a helper
procedure so your definitions can be found in one place.

You can also leave out the optional color definition. If one is not set, the color is defined from the normal color set.

select 'dbr.chart.options', 'label_color', 'Q1', '0x006F00';


select 'dbr.chart.options', 'label_color', 'Q2', '0xFF66CC';
select 'dbr.chart.options', 'label_color', 'Q3', '0x9900FF';
select 'dbr.chart.options', 'label_color', 'Q4', '0x99FFCC';

select 'dbr.chart', 'mscolumn';

select Name, Quarter, sum(Items)


from mydb.TestTable
group by Name, Quarter;

select 'dbr.chart.options', 'label_color', 'Q1', '0x006F00';


select 'dbr.chart.options', 'label_color', 'Q2', '0xFF66CC';
select 'dbr.chart.options', 'label_color', 'Q3', '0x9900FF';
select 'dbr.chart.options', 'label_color', 'Q4', '0x99FFCC';

165
Commands

select 'dbr.chart', 'Column';

select Quarter, sum(Items)


from mydb.TestTable
group by Quarter;

Markers

For scatter charts you can choose the marker for each category.

select 'dbr.chart.options', 'marker', 'category_name', ['Marker'[, size]];

Markers available starting from left bottom:

• CircleShape

• GlassSphereShape

• GlassSphere2Shape

• SolidSphereShape

• SquareShape

• DiamondShape

• TriangleShape

• RightTriangleShape

• LeftTriangleShape

• InvertedTriangleShape

• StarShape(3)

• StarShape(4)

166
Commands

• StarShape(5)

• StarShape(6)

• StarShape(7)

• StarShape(8)

• StarShape(9)

• StarShape(10)

• PolygonShape(5)

• Polygon2Shape(5)

• PolygonShape(6)

• Polygon2Shape(6)

• CrossShape(0.1)

• CrossShape(0.2)

• CrossShape(0.3)

• CrossShape(0.4)

• CrossShape(0.5)

• CrossShape(0.6)

• CrossShape(0.7)

• Cross2Shape(0.1)

• Cross2Shape(0.2)

• Cross2Shape(0.3)

• Cross2Shape(0.4)

• Cross2Shape(0.5)

• Cross2Shape(0.6)

• Cross2Shape(0.7)

Some markers have parameters which alter the marker appearance.

select 'dbr.chart', 'scatter';


select 'dbr.chart.options', 'marker', 'Amrak', 'TriangleShape', 12;
select 'dbr.chart.options', 'marker', 'Baxtor', 'InvertedTriangleShape';
select 'dbr.chart.options', 'marker', 'Detac', 'SquareShape';

select category, x, y
from mydb.mydata
order by category;

167
Commands

Chart value formatting

You can use the normal 'dbr.colstyle'-command to format the image chart values.

Simple trendline

A trendline can be added to XY and scatter charts using trendline-options.

select 'dbr.chart', 'Column', 'Trendline';

select 'dbr.chart.options', 'trendline', '0x008000' , 'Trendline', 5;


/* Add a legend to the trendline */
select 'dbr.chart.options', 'chartdirector','$legendObj = $c->addLegend(50, 8, false, "",
8)->setBackground(Transparent);';

select supplier, sum(items)


from mydata
group by supplier;

168
Commands

Hiding chart elements

You can hide parts of the chart with 'hide'-option. In the example we'll hide the plot background, both axis and
the grid to make a cleaner looking chart with label showing the value.

select 'dbr.chart', 'bar', 'Matching type', 300, 'auto';


select 'dbr.colstyle', 2, '%.1f %';

-- Hide background, both axis and the grid


select 'dbr.chart.options', 'hide', 'bg,yaxis,xaxis,grid';
-- Title aligned to center of chart (instead of plot area)
select 'dbr.chart.options', 'title.align', 'chart';
select 'dbr.chart.options', 'height_per_item', 30;

select 'Automatically matched', 79.2


union
select 'Manually matched', 11.9
union
select 'Unmatched', 8.9;

The result is shown right. The same chart without the options is shown in left.

169
Commands

Curve fitting with ConfidenceBand and PredictionBand

The chartdirector-option has variable $trend_layers which can be used to add functionality to a trendline. In
the example ConfidenceBand and PredictionBand are added.

select 'dbr.chart', 'scatter', 'Scatter chart with trendline, confidence and prediction
band';
select 'dbr.chart.options', 'marker', 'Server AAA', 'TriangleShape', 16;
select 'dbr.chart.options', 'marker', 'Server BBB', 'InvertedTriangleShape', 26;

select 'dbr.chart.options', 'trendline', '0x008000', 'AAA Trend', 4, 'Server AAA';


select 'dbr.chart.options', 'trendline', '0x1EC41B', 'BBB Trend', 4, 'Server BBB';

select 'dbr.chart.options', 'chartdirector',


'$trend_layers[0]->addConfidenceBand(0.5, 0x806666ff);
$trend_layers[0]->addPredictionBand(0.5, 0x8066ff66);
$trend_layers[0]->setRegressionType(PolynomialRegression(2));';

select server, x, y
from mydata;

170
Commands

Sparkline charts
Sparkline charts are charts that can be placed within text. Sparkline charts are often used to present trends and
variations, examples of this include stock prices and temperature.

Sparkline charts in myDBR

Sparkline charts in myDBR use Gareth Watts' jQuery Sparklines-plugin for Splunk Inc. All features present in
the plugin are available in myDBR.

To use the sparklines the data column needs a comma separated list of values in a column. In the example this
is done using MySQL's group_concat-function. Then a CSS class is added to column so that a jQuery call can
reference the column. With a dbr.javascript-command the plugin is called with parameters. The 'onload'
parameter for dbr.javascript makes the jQuery plugin execute after the DOM tree has been created.

select 'dbr.hidecolumns', 1;
select 'dbr.colclass', 'Spark', 'spark';

select 'Sales', group_concat(s) as 'Spark', 'pie'


from (
select quarter(InsertDate) as q, sum(ItemsSold) as s
from TestTable
where year(InsertDate)=2008
group by 1
) sub;

select 'dbr.javascript', "$('.spark').sparkline('html', { type: 'pie', height:


'1.0em' });", 'onload';

171
Commands

Chart examples

Basic XY chart

In the example, we'll generate a simple pie chart. As for any other XY-chart we need to provide X and Y values
for the chart.

select 'dbr.chart', 'Pie', 'Sample Pie chart';

select category, total_sales


from mydb.sales_by_film_category;

A multi series column chart

In multi series charts, we have multiple Y-values. In the following example we'll select data for each quarter for
selected years and make a multi series column chart out of the data.

select 'dbr.chart', 'mscolumn';


select 'dbr.chart.options', 'showValues', 1;

select production_year, production_quarter, value


from mydata;

172
Commands

Transposing a multi series column chart

Multi series charts can easily be transposed, so that the categories and the series will swap places. We'll use
the same query as in previous example and we'll transpose the chart prior showing it. This is done with a chat
option 'chart_transpose'.

select 'dbr.chart', 'mscolumn';


select 'dbr.chart.options', 'showValues', 1;
select 'dbr.chart.options', 'chart_transpose';

select production_year, production_quarter, value


from mydata;

173
Commands

Hierarchical chart

Hierarchical and diagram charts will produce a network chart. In hierarchical chart there is a parent-child
connection, while in diagram-charts there is just a connection between the nodes. Both charts are generated
the same way, the only difference being the chart type.

select 'dbr.chart', 'Hierarchy';

select 'Corporate', 'Sales'


union
select 'Corporate', 'Production'
union
select 'Corporate', 'Management'
union
select 'Sales', 'Northern Sales'
union
select 'Sales', 'Southern Sales'
union
select 'Production', 'Top part production'
union
select 'Production', 'Bottom part production';

174
Commands

Network chart options

Example is a query against the MySQL's sakila-demo database's system tables in order to draw a quick ER-
diagram. The chart is a Hierarchy-chart and with the diagram-option the chart is set to Left-to-Right (see Graphviz
documentation for more info):

select 'dbr.chart', 'Hierarchy';


select 'dbr.chart.gv.style', 'graph', 'rankdir=LR';
select 'dbr.chart.gv.style', 'node', 'shape=box,fillcolor=#CCCCFF,style=filled';

select distinct referenced_table_name, table_name


from information_schema.key_column_usage
where table_schema='sakila' and referenced_table_name is not null
order by referenced_table_name;

Boxwhisker chart

The boxwhisker chart consist of bottom and top values. Optionally you can add min, max and middle values

select 'dbr.chart', 'Hierarchy';


select 'dbr.chart.gv.style', 'graph', 'rankdir=LR';
select 'dbr.chart.gv.style', 'node', 'shape=box,fillcolor=#CCCCFF,style=filled';

select label, box_min, box_max, minim, maxim, middle

175
Commands

from mydb.data;

Floatingbox
A floating box chart is a variation of boxwhisker chart which draws independent boxes for series / label with
min-max

select 'dbr.chart', 'floatingbox', 'floatingbox';

select series, label, box_min, box_max


from mydb.data;

176
Commands

3D Bubble chart

A sample bubble chart with options

declare vTechA varchar(30);


declare vTechB varchar(30);
declare vTechC varchar(30);

select 'dbr.chart', 'bubble3d', '3D Bubble chart', 612, 345;


select 'dbr.chart.options', 'bubble.scale', 'y';

select 'dbr.chart.color', '0x00FF00', '0xFF0000','0x0000FF';

set vTechA = 'Techology A';


set vTechB = 'Techology B';
set vTechC = 'Techology C';

select 150 as 'x', 12 as 'y', 20 as 'r', vTechA as 'name', 'x1' as 'rn'


union
select 30, 60, 50, vTechA, 'x2'
union
select 300, 25, 50, vTechA, 'x3'
union
select 240, 125, 165, vTechA, 'x4'
union
select 50, 35, 30, vTechB, 'x5'
union
select 100, 50, 55, vTechB, 'x6'
union
select 130, 175, 95, vTechC, 'x7';

Chart shading

With the 'shading' option you can use CharDirector's chart shading feature

177
Commands

sselect 'dbr.chart', 'Pie3D', 'Shading Pie chart';


select 'dbr.chart.options', 'shading', 'ConcaveShading';
select 'dbr.chart.options', 'pie_label_format', '0';

select category, total_sales


from mydb.sales_by_film_category;

Donut chart with options

A donut-chart (or you can use alias 'doughnut'), with options. We'll

select 'dbr.chart', 'donut', '', 550, 350;

/* Set the donut thickness */


select 'dbr.chart.options', 'donut.size', 20;
/* Text in the middle */
select 'dbr.chart.options', 'donut.text', 'Income';
/* Font size of the text in the middle */
select 'dbr.chart.options', 'donut.font.size', 24;
/* Label font sizes */
select 'dbr.chart.options', 'label_font_size', 12;

select 'dbr.chart.color', '0x194996', '0x5F77BC', '0x9AA7DA', '0xE6E8F7', '0xF7F7FF';


select 'dbr.colstyle', 'Percentage', '{value} %\n{label}';

select Sector, Percentage


from mydb.income;

178
Commands

Scatter3D chart

A basic chatter chart includes x, y, and z data.

select 'dbr.chart', 'scatter3d';

select x, y, z
from scatter_3d;

179
Commands

MSScatter3D chart with options

A scatter3d chart has multiple options so you can finetune the chart to suit your needs.

/* A scatter chart with multiple options */


select 'dbr.chart', 'msscatter3d', '', 760, 440;

select 'dbr.chart.options', 'axis', 'Date', 'Importance', 'Effect';


select 'dbr.chart.options', 'marker', 'Unsuccessful', 'Cross2Shape()', 15;
select 'dbr.chart.options', 'scatter3d.y_axis_labels', "Low", "Medium", "High";

select 'dbr.chart.color', '0x00ff00', '0x0000cc';

select 'dbr.chart.options', 'scatter3d.plot_area', 385, 210, 400, 280, 240;


select 'dbr.chart.options', 'scatter3d.view_angle', 15, 25;

select 'dbr.chart.options', 'axis_font' ,'arialbd.ttf';


select 'dbr.chart.options', 'axis_font_size' , 10;

select 'dbr.chart.options', 'label_font_size', 8;

select 'dbr.chart.options', 'scatter3d.drop_line', 'Successful', null, 'dot';


select 'dbr.chart.options', 'scatter3d.drop_line', 'Unsuccessful', '0x0000cc', 'altdash';

select label, x, y, z

180
Commands

from msscatter_3d;

Basic Gantt-chart

In the most basic Gantt chart, we have a labels with start and end dates

select 'dbr.chart', 'gantt', 'Gantt';

select label, cast(start as date), cast(end as date)


from (
select 'Market Research' as 'label', '2017-03-16' as 'start', '2017-03-30' as 'end',
'Market' as 'stage'
union
select 'Market Research', '2017-06-02', '2017-06-20', 'Market'
union
select 'Define Specifications', '2017-03-30', '2017-04-13', 'Specification'
union
select 'Overall Archiecture', '2017-04-13', '2017-04-27', 'Specification'
union
select 'Project Planning', '2017-04-20', '2017-05-04', 'Detail Specification'
union
select 'Detail Design', '2017-04-27', '2017-05-11', 'Final Specification'
union
select 'Software Development', '2017-05-04', '2017-06-03', 'Development'
union
select 'Test Plan', '2017-05-25', '2017-06-03', 'Development'
union
select 'Testing and QA', '2017-06-01', '2017-06-22', 'Development'
union
select 'User Documentation', '2017-06-03', '2017-06-22', 'Development'
) as q;

181
Commands

Gantt-chart within a day


If your Gantt-chart data covers only a day, the x-axis shows hours. You can set the scale with the gantt.start
and gantt.end options-

select 'dbr.chart', 'gantt', 'Gantt hours', 600, 150;


select 'dbr.chart.options', 'gantt.scale', 1;
select 'dbr.chart.options','gantt.start', '2000-01-01 06:00:00';
select 'dbr.chart.options','gantt.end', '2000-01-01 21:00:00';

select label, cast(concat('2000-01-01 ',start) as datetime), cast(concat('2000-01-01


',end) as datetime)
from (
select 'Breakfast' as 'label', '07:00' as 'start', '07:20' as 'end'
union
select 'Lunch', '11:00', '10:30'
union
select 'Dinner', '17:45', '18:30'
) as q;

Gantt-chart with options


Gantt-chart has many options which you can use to configure the Gantt-chart.

182
Commands

select 'dbr.chart', 'gantt', 'Gantt with options', 800, 'auto';

select 'dbr.chart.options', 'category_order', 'Extra', 'Detail Specification';


select 'dbr.chart.options', 'category_order', 'Development';
select 'dbr.chart.options','gantt.baseline_text', 'Baseline text';
select 'dbr.chart.options','gantt.baseline_pattern.border', '0x000000'; /* Show no border
for baseline bars */
select 'dbr.chart.options','gantt.baseline_pattern.color', '0x1B32C4'; /* Show baseline
bars in dark blue */
select 'dbr.chart.options', 'gantt.start_of_day_format', '-{value|dd}'; /* Show dates as
"Monthname dd" */
select 'dbr.chart.options','gantt.baseline', 'Market Research', '2017-03-12',
'2017-03-20' /* Add baseline bars */
union
select 'dbr.chart.options','gantt.baseline', 'Overall Archiecture', '2017-04-08',
'2017-04-26';
select 'dbr.chart.options', 'gantt.dateline', '2017-05-09'; /* Add vertical bar */
select 'dbr.chart.options', 'gantt.scale', 30; /* x-axis per month */
select 'dbr.chart.options','height_per_item', 30;

select label, cast(start as date), cast(end as date), stage


from (
select 'Market Research' as 'label', '2017-03-16' as 'start', '2017-03-30' as 'end',
'Market' as 'stage'
union
select 'Market Research', '2017-06-02', '2017-06-20', 'Market'
union
select 'Define Specifications', '2017-03-30', '2017-04-13', 'Specification'
union
select 'Overall Archiecture', '2017-04-13', '2017-04-27', 'Specification'
union
select 'Project Planning', '2017-04-20', '2017-05-04', 'Detail Specification'
union
select 'Detail Design', '2017-04-27', '2017-05-11', 'Final Specification'
union
select 'Software Development', '2017-05-04', '2017-06-03', 'Development'
union
select 'Test Plan', '2017-05-25', '2017-06-03', 'Development'
union
select 'Testing and QA', '2017-06-01', '2017-06-22', 'Development'
union
select 'User Documentation', '2017-06-03', '2017-06-22', 'Development'
) as q;

183
Commands

Meter charts
myDBR offers various types of meter charts (chart that have show one value in a scale): circle meter, semicircle,
rectangular and linear meter. All share same logic and options.

Formatting options for meter charts


You can format various parts of meter charts

• Choose between step and gradient coloring

• Define coloring scale (start, and and steps)

• Define number scale

• Add texts

• Choose between themes

• Set font, font size and font colors for both title and label

• Choose pointer color

Setting steps and gradient colors


You can choose between step and gradient colors.

Using step colors and custom color scales

184
Commands

select 'dbr.chart','meter';
/* Use step colors */
select 'dbr.chart.options', 'meter.color.type', 'step';

/* First step represents where the coloring starts, subsequent steps define next step and
used color */
select 'dbr.chart.options', 'meter.color.step', step, color
from (
select 10 as 'step', null as 'color'
union
select 40, '0xFFFF00'
union
select 70, '0x00FF00'
union
select 100, '0xFF0000'
) as q;

select 60;

Using gradient colors and custom color scales

select 'dbr.chart','meter';
/* Use of gradient colors is done by default, you can also define the color type to
gradient*/
select 'dbr.chart.options', 'meter.color.type', 'gradient';

/* Use custom scale min, max, step */


select 'dbr.chart.options', 'scale', 20, 180, 20;

/* Choose white theme */


select 'dbr.chart.options', 'meter.theme', 'white';

/* Set gradient steps */


select 'dbr.chart.options', 'meter.color.gradient', step, color
from (
select 20 as 'step', '0xd3d3d3' as 'color'
union
select 40, '0xd3d3d3'
union
select 100, '0xa9a9a9'
union

185
Commands

select 180, '0x000000'


) as q;

select 60;

Choosing meter theme


Meter themes (defined in defaults.php: default, white, black) allow defining various aspects of a chart

Using black theme and setting text

select 'dbr.chart','rectangularmeter';
select 'dbr.chart.options', 'meter.text', 'CPU';
select 'dbr.chart.options', 'meter.theme', 'black';
select 'dbr.chart.options', 'scale', 20, 200, 20;

select 'dbr.chart','meter';

select 40;

Vertical linearmeter
You can set the linearmeter to be vertical

186
Commands

select 'dbr.chart','linearmeter';
select 'dbr.chart.options', 'linearmeter.orientation', 'vertical';

select 76;

Hierarchical and diagram charts - using Graphviz


With myDBR's Graphviz-support one can easily create hierarchical and diagram charts and the associated
Graphviz-code. Basic charting can be done without any Graphviz-knowledge. In order to fully exploit Graphviz's
capabilities, please consult the original Graphviz documentation.

Graphviz-charts have chart type of 'hierarchy' or 'network' which you select by dbr.chart-command.

Commands
dbr.chart.gv.style - Defines the default style for the object
dbr.chart.gv.node - Defines the individual node style
dbr.chart.gv.cluster - Defines the individual cluster style
dbr.chart.gv.engine - Selects the layout engine
dbr.chart.gv.renderer_formatter - Selects the renderer and optional formatter for the engine overriding
the default ones, for example cairo:cairo

Syntax

select 'dbr.chart.gv.style', 'graph' | 'node' | 'edge' | 'cluster', style_definition


select 'dbr.chart.gv.node', nodeID, name, style_definition, [clusterID]
select 'dbr.chart.gv.cluster', clusterID, name, style_definition
select 'dbr.chart.gv.engine', engine
select 'dbr.chart.gv.renderer_formatter', renderer[:formatter]

myDBR's Graphviz basics

Nodes represent the connected elements in Graphviz. If no node definitions are given, the chart with it's nodes
is drawn with default Graphviz formatting.

187
Commands

In Graphviz charts there are two options for the data query:

Option 1 where the chart is drawn based on single values / node.

select node1, node2 [, edge_style]


from mydb.Data;

Option 2 where node contains both ID value and the visible value to the user. This can used when making charts
to be exported and you want to keep the IDs.

select node1_id, node2_id, node1_name, node2_name [, edge_style]


from mydb.Data;

Here is a simple example of a hierarchical chart.

select 'dbr.chart', 'Hierarchy';

select 'Corporate', 'Sales'


union
select 'Corporate', 'Production'
union
select 'Corporate', 'Management'
union
select 'Sales', 'Northern Sales'
union
select 'Sales', 'Southern Sales'
union
select 'Production', 'Top part production'
union
select 'Production', 'Bottom part production'
union
select 'Extra', null;

Graph
Formatting needed for the Graphviz graph can be passed through the dbr.chart.gv.style-command.

select 'dbr.chart.gv.style', 'graph', style_definition;

select 'dbr.chart', 'Hierarchy';

188
Commands

select 'dbr.chart.gv.style', 'graph', 'rankdir=LR,splines=false';

select 'Corporate', 'Sales'


union
select 'Corporate', 'Production'
union
select 'Corporate', 'Management'
union
select 'Sales', 'Northern Sales'
union
select 'Sales', 'Southern Sales'
union
select 'Production', 'Top part production'
union
select 'Production', 'Bottom part production';

Node
The nodes can be formatted all with the same formatting or use specific formatting for individual nodes. In the
next example we'll change the default formatting and format selected nodes individually.

select 'dbr.chart.gv.node', nodeID, name, style_definition[, clusterID]

The style_definition is a comma separated list of Graphviz-attributes.

select 'dbr.chart', 'Hierarchy';

/* This will change the default node formatting */

select 'dbr.chart.gv.style', 'node', 'shape=box,fillcolor=#CCCCFF,style=filled';


/* This will change formatting from individual nodes */

select 'dbr.chart.gv.node', 'Sales', 'Sales', 'shape=box3d,fillcolor=red,style=filled';


select 'dbr.chart.gv.node', 'Production', 'Production',
'shape=box3d,fillcolor=red,color=white,style=filled';

select 'Corporate', 'Sales'


union
select 'Corporate', 'Production'
union
select 'Corporate', 'Management'

189
Commands

union
select 'Sales', 'Northern Sales'
union
select 'Sales', 'Southern Sales'
union
select 'Production', 'Top part production'
union
select 'Production', 'Bottom part production';

Subgraph/cluster
Adding clusters to the chart can be done by using 'dbr.chart.gv.cluster' command. In addition to the
cluster itself, the nodes attached to the cluster also needs to be defined.

select 'dbr.chart.gv.cluster', clusterID, name, style_definition

select 'dbr.chart', 'Hierarchy';


select 'dbr.chart.gv.style', 'graph', 'rankdir=TB,splines=true,ranksep=0.8';
select 'dbr.chart.gv.style', 'node',
'shape=box,fillcolor=#CCCCFF,style=filled,fontsize=10';

select 'dbr.chart.gv.node', 'Sales', 'Sales',


'shape=box,fillcolor=red,fontcolor=white,style="rounded,filled",fontsize=10', 1;
select 'dbr.chart.gv.node', 'Production', 'Production',
'shape=box,fillcolor=red,fontcolor=white,style="rounded,filled",fontsize=10', 1;

select 'dbr.chart.gv.cluster', 1, 'Organization',


'style=filled,fillcolor=lightgrey,labelloc=b,fontsize=12';

select 'Corporate', 'Sales'


union
select 'Corporate', 'Production'
union
select 'Corporate', 'Management'
union
select 'Sales', 'Northern Sales'
union
select 'Sales', 'Southern Sales'
union
select 'Production', 'Top part production'
union
select 'Production', 'Bottom part production';

190
Commands

Edge
Passing formatting information to edges can be done simply adding the style information to the node-query.

select 'dbr.chart', 'Hierarchy';

select 'Corporate', 'Sales', 'color=red,arrowhead=empty'


union
select 'Corporate', 'Production', ''
union
select 'Corporate', 'Management', ''
union
select 'Sales', 'Northern Sales', ''
union
select 'Sales', 'Southern Sales', ''
union
select 'Production', 'Top part production', ''
union
select 'Production', 'Bottom part production', '';

191
Commands

Layout engine

myDBR allows you to select the layout engine used by using the command dbr.chart.gv.engine. See the
Graphviz documentation for more info on layout engines and how to choose the most suitable one for your chart.

select 'dbr.chart.gv.engine', engine

Possible engines:

• dot - makes 'hierarchical' or layered drawings of directed graphs (default engine)

• neato - makes 'spring model' layouts (Kamada-Kawai algorithm)

• fdp - makes 'spring model' layouts (Fruchterman-Reingold algorithm)

• twopi - makes radial layout after Graham Wills 97

• circo - makes circular layout, after Six and Tollis 99, Kauffman and Wiese 02

Example of engine usage:

declare vShape varchar(100)

/* Make it a network chart */

select 'dbr.chart', 'network';

/* Use the neato engine */

select 'dbr.chart.gv.engine', 'neato';

/* Prepare the shape, we'll get the color from the data */

select 'shape=octagon,style=filled,fillcolor=' into vShape;

/* Set individual node's color, no label */

select 'dbr.chart.gv.node', id, null, concat(vShape, color)


from mydb.nodes;

/* Get the chart data */

select parent, child


from mydb.node_connections;

circo engine neato engine


select 'dbr.chart.gv.engine', 'circo'; select 'dbr.chart.gv.engine', 'neato';

192
Commands

Example: Same chart drawn with different layout engines.

Notes: Report linking and Graphviz-chart size

Report linking (clicking a node launches another report) is also available for Graphviz charts. The report's
parameters must always be bound to the first column.

select 'dbr.chart', 'network';


select 'dbr.report', 'sp_DBR_NodeZoom','vNodeID=1';

select parent, child


from mydb.node_connections;

If you want to scale the size of a Graphviz-chart, you can use both 'dbr.chart' -commands x,y parameters
or native Graphviz scaling (see size-attribute). If both are applied, myDBR uses the size-attribute.

select 'dbr.chart', 'network';


select 'dbr.chart.gv.style', 'graph', 'size="4,3"';
select 'dbr.report', 'sp_DBR_NodeZoom','vNodeID=1';

select parent, child


from mydb.node_connections;

Linked reports
Commands
dbr.report - Create a link to another report

193
Commands

dbr.url - Create a link to an external URL


dbr.button - Create a button containing a link
dbr.list - Create a list containing a link to a report
dbr.embed_object - Create a placeholder or a popup window for linked report's content
dbr.selectlist - Create a select list for linked reports
dbr.searchable - Create a search field to get dynamic content

Syntax

select 'dbr.report', procedure_name, [ColumnReference, ] [embed_target, ]


[parameter_name=ColumnReference/ParameterReference, ...]
[parameter_name*=ColumnReference/ParameterReference, ...]
[parameter_name<=ColumnReference/ParameterReference, ...]
[parameter_name="constant", ...] [,event=click|dblclick] [,callbefore=callbefore_function]
[,append=url_parameter] [,'"menu title"'], [,show_link=expression] [html5-data-
attribute]
select 'dbr.url', external_url_base, 'URL name', [ColumnReference, ]
[embed_target, ] [<=ColumnReference/ParameterReference to be added to base URL]
[parameter_name=ColumnReference/ParameterReference, ...]
select 'dbr.button', [button text / ColumnReference ], [button class], [button wrapper
class]
select 'dbr.list', [list_class], [menutitle]
select 'dbr.embed_object', embed_target [, embed_class]
select 'dbr.selectlist', default_selection, title[, 'find' [, select_class]]
select 'dbr.searchable', procedure_name[, 'placeholder
text' [parameter_name=ColumnReference/ParameterReference, ...]]

Where:

ColumnReference Optional parameter which the linked report is attached to. If no column is
specified, the linked report is shown in the link-menu that will be automatically
attached to the object. Note that the ColumnReference must be using format
"[column_number]".

embed_target Target embed element for linked report content. embed_target can be a DIV
created with 'dbr.embed_object'-command or one of the predefined names.
(Do not use any special characters, just a-z.). If the object is visible and linked
report fetches data into the object, browser by default scrolls to the object to
show the new data. If object contains CSS class "no_scroll_to", no scrolling is
done. If you add [] to the end of embed_target, the embed_targets is created
automatically (no need to use dbr.embed_object-command). This is useful in
cases where embed_target contains non-visible values, for example a report
returns JavaScript to remove selected line. If a target is a popup, a Cancel-
button can be added to parameter popup by appending '&cancel_button=1'
into the link

procedure_name Refers to another myDBR report's stored procedure

parameter_name Refers to linked stored procedure's / URL's parameter name to which we


want to pass value to

ColumnReference/ Value to be passed to the parameter. Different options include:


ParameterReference
• parameter_name=ColumnReference/ParameterReference The
user is not allowed to change the parameter nor is it shown in parameter
query form

• parameter_name<=ColumnReference/ParameterReference The
parameter becomes editable to the user in the parameter query form

194
Commands

• parameter_name*=ColumnReference/ParameterReference The
parameter is visible in the parameter query form, but the user is now
allowed to change the parameter value

• parameter_name="Constant" Pass a constant value to the parameter


See more info on ColumnReference/ParameterReference at Referencing
columns and parameters.

event=click|dblclick The linked report can be attached directly to a report table cell so that
clicking / double-clicking the cell will trigger the report execution directly. This
option can only be used when 'column' is defined. Using this option uses the
cell onclick/ondblclick-event instead of the href.

callbefore A Javascript function which is executed before the linked report is launched.
If the function returns true the linked report is executed, if it returns false,
no linked report is executed. The function will get the clicked table cell as a
parameter. Callbefore is used in cases where user confirmation is needed
before the linked report execution. For example, if the linked report deletes
the row where the user clicks, the function can ask confirmation for the
delete.

append=url_parameter If you want to add additional parameters to the generated URL, you can
use the 'append'-parameter. For example if you want to make link reference
to PDF document instead of a report add 'append=&export=pdf' as a
parameter.

list_class A CSS class defined in the user/userstyle.css file. Defines the HTML ul/li list
style used. A special 'htlist' for horizontal lists and 'vlist' for vertical lists is
pre-defined and used as the basis for the user's own styling.

embed_class A CSS class defined in the user/userstyle.css file or in the report with
dbr.html. If a special 'popup' value is used, the placeholder is a popup window
allowing multiple separate popups to be used in a report.

default_selection A default selection in the select list

'find' Select list will be searchable if this constant is set.

"menu title" If linked report is shown in a menu, the menu item can be defined here.

show_link=expression If a a PHP expression evaluates to true, the linked report is placed on


object. The expression is any valid PHP expression that can contain
ColumnReferences. Defines if link is created based on the data.

html5-data-attribute A link to a raport can be put in a html5 data-attribute with this. By setting
string "html5-data-callback", the link to the report will be placed to a "data-
callback" attribute. This allows scripts to access the link (for example editing
callback).

Explanation
One of the powerful features of myDBR is the ability to link reports together allowing drill-down reports. A linked
report can be attached to any object in a report (column, table, chart, graph). Report links can point to another
report or to an external web-page.

The linked report can also be embedded in an existing report by using an embedded element or a popup window.
This allows quick drill-down content to be shown to the user without the need for the user to jump between the
reports. The content of the linked report is fetched dynamically. To embed a linked report, the embed_target-
parameter needs to be set.

195
Commands

Linking starts with the dbr.report-command (or dbr.url if linking to external source) followed by a normal
result set. When the dbr.report-command is shown, the linked report is attached to the next result set. The
dbr.report-commands parameters will define the linked report, including where the link is attached to, where
the content of linked report is shown and also the required parameters.

Linking to an external URL using dbr.url works similarly to dbr.report. The only difference is that the
command requires the URL's visible name to be defined.

Basic use of linking:

select 'dbr.report', 'sp_DBR_film';

select Title, fid


from mydb.film_list

Linked report parameters

The linked report itself is a stored procedure that might have parameters. Parameters can be taken from
the original report's incoming parameters and or the actual data shown in the report. If the linked report has
parameters that are not populated during the linking, these parameters are asked from the user.

Adding a parameter to linked report. (In this case the inFilmID is a parameter for the sp_DBR_film stored
procedure):

select 'dbr.report', 'sp_DBR_film','inFilmID=fid';

select Title, fid


from mydb.film_list

Linked report placement

By default, a linked report will attached to the object via an link-menu (the user sees an

icon). With tabular reports, the link can also be attached directly to a column by giving the column-number as
a parameter.

A linked report is attached to first column

select 'dbr.report', 'sp_DBR_film', '[Title]', 'inFilmID=fid';

select Title, fid


from mydb.film_list

Output destination of the linked report

By default, a linked report will execute the new report and the user's browser will show the new report. The user
can navigate between the reports using browsers back and forward buttons.

The linked report content can also be embedded to the report by using fixed embed element or a popup window
user is able to move. Benefit of doing this is that the user does not need to jump between the reports if more
information is needed.

The output destination can also be a new browser window when a predefined value of 'new_window' is used.
A dynamic popup can be used when a predefined value of 'new_popup' is used.

196
Commands

The embed_target-parameter can also contain column references (using [ColumnReference] notation). This
allows multiple embedded elements to be shown dynamically at the same time.

The embed_target-parameter has the following formats:

mytarget Will use the 'mytarget' (or whatever name you choose to use) DIV defined
by dbr.embed_object-command. When the user clicks the link, content
of the 'mytarget' is replaced with the new content

mytarget[] myDBR will automatically create a DIV with id mytarget (or whatever
name you choose to use) if one is not defined. No need to create one
dbr.embed_object-command. Most suitable in cases where a linked
report returns nothing or returns JavaScript not visible to user.

popup A predefined name popup will open a popup dialog for content

new_popup A predefined name new_popup will open a new popup dialog for each
individual linked window

popup[_whatever] Will dynamically create a new popup window for each ID (you can specify
[ColumnReference] multiple columns). Allows identifying the popups that when a user clicks the
same linked report in a different row, each of them open up in a separate
window. For example if the ColumnReference points to customerID 1 and 2,
and the target would be popup_customer[CustID], the dynamically created
popups, would get the names popup_customer1 and popup_customer2.
This would allow the user for example to compare customers together in
separate popups.

new_window A predefined name new_window will open a link into new browser window

mytarget[ColumnReference1] When a user clicks a row, where the column reference is '2012', it will use
[ColumnReference2] the 'mytarget2012' as the target (you can use multiple column references
if you like). If the target has not been created using dbr.embed_object,
the target will be created dynamically to the end of the report. With
dbr.embed_object one can determine the placement.

inline A predefined name inline will display the linked report in a row below the
linked row. A new row is added to the table report where the content is shown.
This link type is available in table reports. Use this when you quickly want to
open additional information from a row without losing the user context from
the main report.

mytarget.myid[ColumnReference1]When a user clicks a row, where the column reference is '2012', it will create
a target myid2012 inside target mytarget. The 'myid' element is a text string
making sure the id is unique. If the myid2012 element has not been created
using dbr.embed_object, it will be created dynamically.

mytarget.myid[ColumnReference1].classname
This is the same as the previous, but with additional classname for myid2012
target. For example 'kwn'-class (keepwithnext) makes linked elements
appear side by side inside the mytarget element.

popup_parameter A predefined name popup_parameter. If a linked report has user enterable


parameters, parameters will be asked using a popup window. The linked
result will be shown in new page. Use only with report with parameters. If
used with a linked report with no parameters, result will be shown in popup.

popup_parameter_new_window A predefined name popup_parameter_new_window-prefix. If the linked


report contains parameters that needs to be asked from the user, the
parameters are asked in a popup-window and the linked report is opened

197
Commands

in a new window. Use this when you know the user might cancel the report
after viewing the paramerter dialog so user remains in the main report.

embedded_report_[_whatever] A predefined embedded_report_-prefix. The linked report is embedded


[ColumnReference] into the current report. If the linked report has parameters that needs to be
asked from the user, the parameter form is shown in the report. Use this
when you want to include another report into an existing report in a way that
user can re-run the embedded report with different parameters.

Optional links based on data


Links can be made optional by adding 'show_link' parameter to the command. A show_link parameter can be
any valid PHP expression that can also contain ColumnReferences. if the expression evaluates to true, the link
is shown, otherwise not.

Examples of show_link are: 'show_link=[myColumn]=="disable"', 'show_link=[myColumn]' or


'show_link=[myColumn]>10'.

Links can also be made optional by adding rowclass / cellclass no_link to the row / cell. Rows / cells with this
class will not have links attached. no_link-will disable all links to the defined row.

Examples

Basics of linking

We have a film list from which we want to pick one film and obtain more details from it.

The film list is shown with a simple query:

select Title, fid


from mydb.film_list

The report (sp_DBR_film) showing the details and the one we wish to link existing report to has one parameter
inFilmID which is the film's ID.

create procedure sp_DBR_film ( inFilmID int )


begin

select description, release_year


from mydb.film
where film_id = inFilmID;

end

198
Commands

Then we can link the sp_DBR_film-report to the existing report with the dbr.report-command and give the
parameter 'inFilmID' value which will be taken from the user's selected row's second column.

select 'dbr.report', 'sp_DBR_film','inFilmID=fid';

select Title, film_id


from mydb.film;

When the original report is executed, the user will see a mark indicating a linked report

and when opened, presents a list of linked reports. The name shown in the list is the name given to the report
when it was added to myDBR. The linked report needs to be added to myDBR in order it to show in the linked
report list.

The list of linked reports shown in the pull-down menu depends on the user's permissions. The list shows only
those reports the user has access to.

Passing multiple parameters


Linked reports can have multiple parameters and also values from the original report's own parameters. In many
cases when doing drill-down reports, some parameters need to be carried over to the next report. The following
example illustrates this situation:

The original report has couple of parameters itself:

create procedure sp_DBR_rentals ( inStartDate date, inEndDate date)


begin

select s.first_name, s.last_name, count(*), s.staff_id


from mydb.rental r
join mydb.staff s on s.staff_id=r.staff_id
where r.rental_date between inStartDate and inEndDate
group by s.first_name, s.last_name, s.staff_id;

end

The linked report has also parameters:

create procedure sp_DBR_rentaldetail (


inStaff_id int,
inStartDate date,
inEndDate date
)
begin

199
Commands

select r.customer_id, r.inventory_id, r.rental_date


from mydb.rental r
where r.rental_date between inStartDate and inEndDate and r.staff_id = inStaff_id;

end;

In order to link the report sp_DBR_rentaldetail to be called from sp_DBR_rentals we need to add that link and
define the parameters:

create procedure sp_DBR_rentals ( inStartDate date, inEndDate date)


begin
select 'dbr.report', 'sp_DBR_rentaldetail','inStaff_id=staff_id',
'inStartDate=(inStartDate)', 'inEndDate=(inEndDate)';

select s.first_name,
s.last_name,
count(*),
s.staff_id
from mydb.rental r
join mydb.staff s on s.staff_id=r.staff_id
where r.rental_date between inStartDate and inEndDate
group by s.first_name, s.last_name, s.staff_id;

end

The 'inStaff_id'-parameter will get it's value from 'staff_id'-column from result set whereas the dates a carried
over from original parameters (parameter name in parentheses).

Output destination of the linked report example

When using an embedded element a dbr.embed_object-command needs to be used to create the


placeholder for the linked report's content.

The content of the linked report will be shown in an embedded element placed after the original data.

select 'dbr.embed_object','shared_embed';
select 'dbr.embed_object','embed_with_id';

-- Will open the link to predefined 'popup'


select 'dbr.report', 'sp_DBR_link_location_drill', 'popup', '[shared_popup]', 'inID=ID';

-- Will open the link always to new popup. No need to declare the new_popup
select 'dbr.report', 'sp_DBR_link_location_drill', 'new_popup', '[new_popup]', 'inID=ID';

-- Will open the link to popup with ID. No need to declare the popup
select 'dbr.report', 'sp_DBR_link_location_drill', 'popup[ID]', '[popup_id]', 'inID=ID';

-- Will open the link always to same embedded object. We declared shared_embed
select 'dbr.report', 'sp_DBR_link_location_drill', 'shared_embed', '[shared_embedded]',
'inID=ID';

-- Will open the link inside an embedded object (ID). We declared the placeholder embed_id
select 'dbr.report', 'sp_DBR_link_location_drill', 'embed_id.target[ID].kwn',
'[embedded_id]', 'inID=ID';

-- Will open the link always to new window


select 'dbr.report', 'sp_DBR_link_location_drill', 'new_window', '[new_window]',
'inID=ID';

200
Commands

-- Will open the parameter form in a popup and open redirect the user to the linked report
select 'dbr.report', 'sp_DBR_film_detail', 'popup_parameter', '[popup_redirect]',
'inID=ID';

-- Will open the parameter form in a popup and open the linked report in a new window
select 'dbr.report', 'sp_DBR_film_detail', 'popup_new', '[popup_new]', 'inID=ID';

-- Will embed the report (including parameter form into the current report)
select 'dbr.report', 'sp_DBR_film_detail', 'embedded_report_film_detail',
'[embed_report]', 'inID=ID';

select film_id as 'ID',


'Shared popup' as 'Shared popup[shared_popup]',
'Always new popup' as 'New popup[new_popup]',
'Popup by ID' as 'Popup by ID[popup_id]',
'Shared embedded' as 'Shared embedded[shared_embedded]',
'Embedded by ID' as 'Embedded by ID[embedded_id]',
'New window' as 'New window[new_window]',
'Ask parameters in this report - redirect to new' as 'Popup - Redirect[popup_redirect]',
'Ask parameters in this report - open in new window' as 'Popup - New[popup_new]',
'Embedded report' as 'Embedded report[embed_report]'
from film
limit 10;

select 'dbr.embed_object','embedded_report_film_detail';

Linking to external webpages with dbr.url

The syntax of dbr.url is similar to dbr.report. The difference in usage is that external URL's do not have
permissions so all external links are available to all users.

We'll assign a URL to email-column (third parameter for the dbr.url) of the query. Second parameter (URL name)
is used when the URL is displayed in a menu (multiple linked reports attached to a column or no link position
column is specified). Data from rows can be embedded into the url by adding ColumnReference inside a bracket
in the external_url_base.

select 'dbr.url', 'http://www.mydbr.com/forums/topic.php?


id=[topic_id]#post[topic_last_post_id]', 'Show topic', '[email]';

select u.topic_title as 'Title',


u.user_email as 'email,
t.topic_id,
t.topic_last_post_id
from forums.bb_topics t
join forums.bb_users u on u.ID = t.topic_last_poster
order by topic_time desc

Will produce URL: http://www.mydbr.com/forums/topic.php?id=158#post-686 when user clicks a email-column


in a row where topic_id=158 and topic_last_post_id=686.

Linked reports and charts

You can also assign linked reports to charts. The report is connected to a chart element (bar/line/node).

Note
Flash-charts have a limit of a single linked report. If the report has multiple reports linked to a flash-
chart, the first one is always used. The Premium version's image charts supports unlimited number of
linked reports per chart.

201
Commands

The following table represents the supported linking in charts.

Chart type Chart command Fusion Chart Graphviz


Charts Director
Column column CL CL
3D Column column3d CL CL
Multi-Series column mscolumn CL CL
3D Multi-Series column mscolumn3d CL CL
Stacked Column stackedcolumn CL CL
3D Stacked Column stackedcolumn3d CL CL
Stacked Bar stackedbar CL CL
3D Stacked Bar stackedbar3d CL
Stacked Area stackedarea CL CL
3D Stacked Area stackedarea3D CL
Line line CL CL
3D line line3d CL
Multi-Series Line msline CL CL
Spline spline CL
Pie pie CL CL
3D Pie pie3d CL CL
Bar bar CL CL
3D Bar bar3d CL CL
Multi-Series Bar msbar CL CL
Area area C CL
3D Area area3d CL
Multi-Series Area msarea CL CL
Donut donut CL CL
3D donut donut3d CL
Multi-Series Column Line Double Y mscolumnlinedy CL CL
3D Multi-Series Column Line Double Y mscolumnlinedy3d CL CL
Meter meter C
Hierarchy hierarchy CL
Diagram diagram CL
C ... Chart supported, L ... Linking supported

Simple chart linking

Charts are always based on a single selection set. The linked reports are linked to this result sets particular row.

Let's examine a simple case where a report is linked to a pie chart. The report itself is a simple one:

select 'dbr.report', 'sp_DBR_LinkedReport', 'vCode=code';


select 'dbr.hidecolumns', 'code';
select 'dbr.chart', 'pie';

select "First", 10, 1 as '[code]'


union

202
Commands

select "Second", 21, 2


union
select "Third", 35, 3
union
select "Fourth", 44, 4;

The report has a result set with three columns: text expression, value and a key ID. > The linked report is called
with the invisible key ID (column 'code').

Report will produce a pie chart with a linked chart attached to the slices. Column references (like vCode=code),
refer to the particular row the user clicks ("Second" -> vCode's value becomes 2)

Buttons as links
Explanation

Sometimes when designing a report network and there is a need to link to a single report, a direct link to another
report is easiest done with a button link. A button link acts as a standard HTML button and will contain a direct link
to the desired report with predefined parameters. The syntax of the button link is similar to normal linked report
with addition of the dbr.button-command. The button text can contain the linked reports name, a free text
defined in dbr.button-command or a column reference when multiple buttons are generated. The default css-
class for the button is 'button'. You can add/replace this with your own class definition via a second parameter
for dbr.button-command. A button element is wrapped into a wrapper div, which you can style with the third
wrapper class-parameter.

Example

Make a button-link to a customer given as parameter.

select 'dbr.report', 'sp_DBR_Customer', 'inCustomerID=1';


select 'dbr.button', 'Show customer info';
select vCustomerID;

This will generate a button-link to the sp_DBR_Customer report and passes the 'vCustomerID' on as an input
(inCustomerID parameter for sp_DBR_Customer-report). You can see an example use of this in the demo-
database.

203
Commands

Select lists as links

Example

A linked report can also be attached to a select list. In the example a linked report is called when user selects
an item from the list.

select 'dbr.report', 'sp_DBR_show_continent', 'inContinent=Continent';


select 'dbr.selectlist', 'Europe', 'Select title', 'find';

select distinct Continent


from demo_country;

This will generate a select list with attached linked report. sp_DBR_show_continent-report will be run when user
selects an item from the list.

Lists as links

Explanation

A list link is a link used mostly with embedded reports. The list visible text will be the first column of the result set.

A list link can be styled by a user defined CSS class in user/userstyle.css. myDBR comes with two example
styles: 'hlist' for horizontal lists and 'vlist' for vertical lists. These can also be used as a basis for the user's own
definitions.

Example

Make a list-link and show the list of continents. The second column (sum(Population)) in the example is used
to define the sorting order for the list items.

select 'dbr.report', 'sp_DBR_list_example', 'continent', 'inContinent=Continent';


select 'dbr.list', 'hlist';

select Continent, sum(Population)


from demo_country
group by Continent
order by 2 desc;

select 'dbr.embed_object', 'continent';

This will generate a list of horizontal links and the content of the linked report will be shown in the 'continent'
object.

204
Commands

Example

This is an example with the list shown as a menu. By providing the menu title as a second parameter, the list
is shown as a menu.

select 'dbr.report', 'sp_DBR_list_example', 'continent', 'inContinent=Continent';


select 'dbr.list', 'hlist', 'Select continent';

select Continent, sum(Population)


from demo_country
group by Continent
order by 2 desc;

select 'dbr.embed_object', 'continent';

This will generate a list of horizontal links and the content of the linked report will be shown in the 'continent'
object.

When the user clicks the menu, it will be expanded as a selection:

205
Commands

Searchable
Explanation

Command dbr.searchable creates a searchable field and the report output is dynamically fetched when user
types the search term.

The example shows how to use dbr.searchable to fetch dynamic content. You can also use dbr.searchable to
find items to be added to current selection.

select 'dbr.searchable', 'sp_DBR_search_data', 'Filter text', 'in_id=id';

select 2 as 'id';

The search report can be a full myDBR report. Un the example we just search for single sample data.

create procedure sp_DBR_search_data(


in_search varchar(30),
in_id int
)
begin

select 'dbr.title', '';


select 'dbr.search', 0;

select
title as 'Title',
description as 'Description'
from film
where title like concat('%', ifnull(in_search,""), '%') or description like concat('%',
ifnull(in_search,""), '%')
limit 10;

end

Optional links
Explanation

Link can be made optional by adding a show_link parameter. The show_link parameter can contain any PHP
expression with column references. If the expression evaluates to true, the link is shown, otherwise not.

206
Commands

Example

select 'dbr.report', 'sp_DBR_show_data', 'inID=ID', 'show_link=[Value]>0';

select ID, Name, Value


from mydata;

The [Value] for the first row evaluates to 0 resulting false expression "0>0". The link is not shown for the first row.

Editable reports

Commands

dbr.editable - Prepares a column so it is in-place editable


dbr.upload - Upload a file to the server's filesystem
dbr.upload.options - Set an upload option
dbr.selectable - Convert an integer ID column to a selectable row to be used with a report linked button

Syntax

select 'dbr.editable', ColumnReference, procedure_name, [,parameter_name=paramref]


[,type=input_type] [,select=query] [,options={'jeditable_options'}]
select 'dbr.upload', path_to_directory, upload_sp [, parameters]
select 'dbr.upload.options', option, value
select 'dbr.selectable', ColumnReference

Where:

ColumnReference The column which will be made editable

procedure_name Editing report's procedure. Permissions to this report determine if the user
is allowed to edit the column

parameter_name Refers to a editing stored procedure's / URL's parameter name to which we


want to pass value to

ColumnReference/ A column value or a parameter value to be passed on to the editing report


ParameterReference as a value for parameter_name.

type Allows you to choose from special input types: 'textarea',


'autosize' (autosizing textarea), 'select', 'select_find', 'radiobutton',
'datepicker', 'datetimepicker', 'timepicker', 'colorpicker', 'richtext' and code
editing specific types 'html', 'php', 'javascript', 'css' and 'sql'. If no input type
is specified, a normal input-field is displayed. Type 'select_find' is a selectlist
with search functionality. For code editing specific types, enable the 'Code

207
Commands

editing' report extension so the editor component will be included into the
report.

select Defines the selection query used when the type is select or radiobutton. The
query should return the ID and user visible value. The query can be a direct
select query or a stored procedure call. The stored procedure call can use
automatic parameters and its parameters may refer to result set columns
and report parameters. If you use 'type=select' or 'type=select_find', you can
use opgroups by specifying the group as thrid column in the select query.

options myDBR uses Jeditable to make cells editable and it's parameters can be
passed on with options

additional options For 'type=radiobutton' you can use 'autosubmit':1 (does not display OK and
Cancel buttons) and 'display':'inline' which will place items side-by-side

path_to_directory Full path to server directory where the uploaded files will be stored

upload_sp Procedure which will be called once the upload is done

upload option To configure the upload functionality

• title Title shown in upload

• noreplace Prevent overwriting files (value = 1)

• accepted_files Comma separated list of accepted file extensions

• maxfilesize maximum size of the uploaded file in megabytes

Explanation
A report column can be marked as editable (in-place editing) with the dbr.editable-command. The command
takes column number and parameter references as parameters. When the user clicks on the editable column,
an in-place editor is shown and the edited value with specified parameters are sent to the procedure that was
given as a parameter. The procedure can perform the update or reject the update and return the original value.

Preventing editing certain cells


Sometimes not all rows in a column or columns in crosstab should be edited. You can prevent editing on selected
cells by adding show_link-parameter to the dbr.editable command. You can also use 'no_edit'-class to the cell
by using the dbr.cellclass-command.

(If you wish to edit more than one column at a time see Creating editable reports for more info.)

Using options
With options you can:

• Change the type of the editable field to something other than a basic input field. Currently textareas are
supported.

select 'dbr.editable', 'col', 'sp_DBR_budget_edit_comment', 'inID=is', 'inQuarter=Q',


'type:textarea', "options={'rows':6,'cols':20}";

• Define the size of the editable field

208
Commands

select 'dbr.editable', 'col', 'sp_DBR_budget_edit', 'inId=id', 'inQuarter=Q',


"options={'height':20}";

• Provide a callback javascript method to be called after the editing is done. myDBR provides two ready-
made callback methods: autosum_int (integers) and autosum_float (decimal numbers) which will refresh the
summary column for the edited column.
Usage:

select 'dbr.editable', 'col', 'sp_DBR_budget_edit', 'inId=id', 'inQuarter=Q',


"options={'height':20, 'callback':autosum_int}";

myDBR also offers callback helper functions which allow you to make updates to other columns based on the
user editable cell. Following list of javascript-functions are available:

• col_value_get( obj[, column [, decimals [, value [, prefix [, suffix]]]]] )


get a value for cell. With no decimals defined deals with integers. The column can be the column index
or a class.

• col_value_set( obj[, column [, decimals [, value [, prefix [, suffix]]]]] )


set a value for cell. With no decimals defined deals with integers. The column can be the column index
or a class.

• ct_total( obj[, NULL [, decimals [, value [, prefix [, suffix]]]]] )


Calculate horizontal aggregate from first parameter's cell. The first parameter should point to first data
column.

• col_value_text(obj [, column[, value]])


get/set textual column value. The column can be the column index or a class.

• col_sum( obj [, column [, decimals[, prefix[, suffix]]]] )


Returns the sum of the column. column can be column index or a class. The column can be the column
index or a class.

• autosum_int( obj, [colindex [, prefix[, suffix]]] )


Updates the sum of the column. If no column is defined the user editable column is updated. The column
can be the column index or a class.

• autosum_float( obj, [colindex [, decimals [, prefix[ , suffix]]]] )


Updates the sum of the column as a decimal number. If no column is defined the user editable column is
updated. The column can be the column index or a class.
obj is reference to the edited cell (javascript 'this').

Basic example
In the example, we'll define the in-place editing to be available in a following cross-table report. We'll
use the dbr.editable command to mark column 4 (Budget) to be updateable with the procedure
sp_DBR_update_crosstable.

Parameters for the command in the example are:

• id
The column to be edited

• sp_DBR_update_crosstable
The myDBR report the edited value is passed to

• inCategory=cat
sp_DBR_update_crosstable's inCategory-parameter is passed the value for selected 'cat' column value
(Category)

209
Commands

• inWeek=Week
sp_DBR_update_crosstable's inWeek-parameter is passed the value for selected 'Week' column value
(payment_week)

CREATE PROCEDURE `sp_DBR_InPlaceEditing


BEGIN

select 'dbr.editable', 'Budget', 'sp_DBR_update_crosstable', 'inCategory=cat',


'inWeek=week';

select 'dbr.crosstab', 'Week';


select 'dbr.count', 'cat';
select 'dbr.sum', 'Total';
select 'dbr.hsum', 'Total';
select 'dbr.hidecolumns', 1;

select category as 'Film category[cat]',


payment_week 'Week',
amount as 'Total',
budget as 'Budget',
category_id
from film_budget;

END

The report that is doing the actual updating can either reject the update and return the original value or simply
update the new value. The report gets all parameters specified in the dbr.editable-call and an additional
parameter for the value.

The last parameter for the editing procedure is automatically populated by the value of edited field. You can
name the parameter as you like (inValue in the example).

CREATE PROCEDURE `sp_DBR_update_crosstable`(


inCategory int,
inWeek int,
inValue float
)
BEGIN

/* Check the data */


if (inValue>0) then
/* Accept the update, no need to return a value */
update film_budget
set budget = inValue
where category_id=inCategory and payment_week=inWeek;
else
/* Reject the update, return the original value */
select budget
from film_budget
where category_id=inCategory and payment_week=inWeek;
end if;

END

In the example, we'll define the in-place editing to be available in a following cross-table report (Budget column
under weeks).

210
Commands

Examples of input types


We'll use different input types for the following data: a plain input, a textarea (autosizing), a select list, radio
buttons, a datepicker and a colorpicker. Dates are shown as is from the database.

For the radio button and select list the textual representation shown to the user will be fetched. myDBR will
pass the ID to the editing report.

CREATE PROCEDURE `sp_DBR_update_inputtype`()


BEGIN
select 'dbr.pageview';

select 'dbr.javascript', '


function color_callback(settings, cell)
{
/*
Chosen (format #626262) value is in 'this'
colorpicker.convert(this) will convert the color value into visible color
*/
colorpicker.convert(this);
}';

select 'dbr.editable', 'Basic', 'sp_DBR_input_edit', 'inId=id';


select 'dbr.editable', 'autosize', 'sp_DBR_text_edit', 'inId=id', 'type=autosize';
select 'dbr.editable', 'select', 'sp_DBR_varchar_edit', 'inId=id', 'type=select',
"select=select id, value from char_values";
select 'dbr.editable', 'radio', 'sp_DBR_integer_edit', 'inId=id', 'type=radiobutton',
"select=sp_radiovalues";
select 'dbr.editable', 'Date', 'sp_DBR_date_edit', 'inId=id', 'type=datepicker';
select 'dbr.editable', 'color', 'sp_DBR_color_edit', 'inId=id', 'type=colorpicker',
"options={'callback':color_callback}";

select 'dbr.hidecolumn' 'id';

211
Commands

select e.plain_column as 'Basic Input[Basic]',


e.text_column as 'Textarea[autosize]',
c.value as 'Select list[select]',
i.value as 'Radio Button[radio]',
e.date_column as 'Date',
e.color as 'Color[color]', /* color format: #626262 */
id
from mydb.editable e
join int_values i on i.id = e.integer_column
join char_values c on c.id = e.char_column;

END

Table int_values and it's associated sp_radiovalues looks like this:

select * from int_values;

id name
-----------
1 'Asia'
2 'Europe'
3 'North America'
4 'Africa'
5 'Oceania'
6 'South America'
7 'Antartica'

CREATE PROCEDURE sp_radiovalues()


BEGIN

select id, name


from int_values;

END

212
Commands

Updating procedures get two parameters. First the supplied 'id' parameter from first column of the result set
and the user supplied value with the specific datatype. The update procedures can include checks for the input,
update the data and optionally return a value which will replace the user input.

For the date column we'll do a direct update

CREATE PROCEDURE sp_DBR_date_edit (


inId int,
inUservalue date
)
BEGIN

update mydb.editable
set date_column = inUservalue
where id=inId;

END

For the datetime we for example can check if the date belongs to the current year and accept / reject the update
based on that.

CREATE PROCEDURE sp_DBR_datetime_edit (


inId int,
inUservalue datetime
)
BEGIN

/* Does the user date belong to current year? */


if ( year(inUservalue) = year(now()) ) then
update mydb.editable
set datetime_column = inUservalue
where id=inId;
else
/* Do not update and return the original data back to report */
select datetime_column
from mydb.editable
where id=inId;
end if;

END

myDBR uses the ID's of the user selectable radio buttons. If this update would be rejected and ID converted,
myDBR will automatically convert the ID back into user visible value.

CREATE PROCEDURE sp_DBR_integer_edit (


inId int,
inUservalue int
)
BEGIN

update mydb.editable
set integer_column = inUservalue
where id=inId;

END

Select works just like the radio button automating the conversion between id's and user visible values.

213
Commands

CREATE PROCEDURE sp_DBR_varchar_edit (


inId int,
inUservalue varchar(5)
)
BEGIN

update mydb.editable
set varchar_column = inUservalue
where id=inId;

END

Passing parameters to a parameter query

When stored procedures are used in dbr.editable select parameters, you can pass parameters to it using normal
column references.

CREATE PROCEDURE `sp_DBR_update_inputtype_parameter`()


BEGIN
select 'dbr.pageview';

select 'dbr.editable', 'Select', 'sp_DBR_integer_edit', 'inId=id', 'type=select',


"select=sp_select_with_params [id]";

select id,
date_column as 'Date',
datetime_column as 'Datetime',
i.value as 'Radio Button[radio]',
c.value as 'Select'
from mydb.editable e, int_values i, char_values c
where e.integer_column = i.id and e.char_column = c.id;

END

Example of basic callback usage

Auto updating the summary columns with the supplied autosum_int / autosum_float requires you to just to define
the predefined callback function. After the editing is done, a new summary value is calculated.

Setting the onblur option to empty makes the 'OK'- and 'Cancel'-buttons to appear below the enterable field.

select 'dbr.editable', 'value', 'sp_DBR_budget_edit', 'inAccount=account',


"options={'onblur':'', 'callback':autosum_int}";
select 'dbr.sum', 2;

select account, value


from budget;

Example of own callback function and the onsubmit

In the example we have an editable column and a column that holds the calculated value of other columns.
When a user updates a column, we need to calculate new calculated value and refresh the summary columns.
In the example we'll use myDBR built in functions col_value_get and col_value_set which will get and set table
cell value for a given cell.

The example also checks if the entered value is bigger than 100 and asks confirmation from the user. This is
done by setting own handler for the onsubmit event.

214
Commands

The 'col_value_get'-function has the following format: col_value_get( obj, col ), where obj is the
reference to the cell and col is the column class in the row if another column than the object's own column is
referenced.

The 'col_value_set'-function has the following format: col_value_set( obj, col, decimals, val,
prefix, suffix ), where 'obj' is the reference to the cell and col is the column class in the row if other
column than the object's column is referenced. 'val' is the value to insert to set and prefix and suffix are additional
text to be attached to the cell value.

The autosum-functions have following formats:


autosum_int( obj, column, prefix, suffix )
autosum_float( obj, column, decimals, prefix, suffix )

When the first row's B column is updated following callback will calculate the cells marked in red.

select 'dbr.javascript', 'function mycallback()


{

// Value of A in edited row


var A = col_value_get( this, "Acol" );

// Value of B in edited cell


var B = col_value_get( this );

// Set the value of 4th A+B column


col_value_set( this, "ABcol", 0, A+B);

// Calculate sum of edited column


autosum_int(this);

// Calculate sum of A+B column


autosum_int(this,"ABcol");

}
function mysubmit(settings, cell)
{
var edited_value;

edited_value = Cell_data.get_value_raw( $(cell).find("input").val(), "int" );

if ( (edited_value>100) && !confirm("Do you to set the value this high ("+
$(cell).find("input").val()+")?")) {
cell.reset();
return false;
}
return true;
}

';

215
Commands

select 'dbr.sum', 'A', 'B', 'AB';


select 'dbr.editable', 'B', 'sp_DBR_edit_B', 'inKey=[ID]',
"options={'callback':mycallback,'onsubmit':mysubmit}";

select 'dbr.colclass', 'A', 'Acol';


select 'dbr.colclass', 'A+B', 'ABcol';

select ID, A, B, A+B as 'A+B'


from mytable;

Example of using dbr.selectable

dbr.selectable converts an ID column of a result set to checkbox, which can be used to mark the rows to be
processed. The selected row's ID's can be used in a button linked report. The result set to be used will be
marked with the dbr.resultclass. Note that the selected ID's are user given values, so you should not trust the
values and should validate the values in the linked report if needed.

Convert an integer ID column to checkboxes and mark the result with dbr.resultclass. The list of ID's are passed
as a parameter to the report attached to a button via the selectable.resultclass syntax:

select 'dbr.selectable', 'ID';


select 'dbr.resultclass', 'films';

select
f.film_id as 'ID',
f.title as 'Title',
c.name as 'Category'
from films f
join category c on c.category_id = f.category_id;

select 'dbr.button', 'Set category';


select 'dbr.report', 'sp_DBR_film_category_set', 'dynamic_div[]',
'in_ids=selectable.films';

select 'dummy';

216
Commands

The ID's are passed in as a comma separated string ("1,2,3,4"). At the end we'll refresh the main report with
dbr.refresh

create procedure sp_DBR_film_category_set(


in_ids text,
in_category_id int
)
begin

update films
set category_id = in_category_id
where find_in_set(films.film_id, in_ids);

select 'dbr.refresh';

end

217
Commands

To refresh the list with selected values, one has multiple choises:

1. Use dbr.refresh to reload the whole report

2. Embed the element with dbr.report and use a hidden button to trigger the element refresh

3. Use direct JavaScript to refresh the values (can be used when the values are not used in another dbr.report/
dbr.url)

To use direct JavaScript to change the visible values

create procedure sp_DBR_film_category_set(


in_ids text,
in_category_id int
)
begin
declare v_category_name varchar(50);

update films
set category_id = in_category_id
where find_in_set(films.film_id, in_ids);

-- Get the name


select name into v_category_name
from category
where category_id = in_category_id;

-- Escape the v_category_name if it can contain backslashes or '-characters, if not, you


can skip this
set v_category_name = replace(v_category_name, "\\", "\\\\");
set v_category_name = replace(v_category_name, "'", "\\'");

select 'dbr.javascript', concat("selected.set_col_value('films', '",in_ids,"', 'category',


'",v_category_name,"')");

end

The selected.set_col_value is a helper function which has a format of


selected.set_col_value(table_class, comma_separated_id_string, column_class,
visible_value);.
It changes the value for column_class colum for all rows whose ID matches with the supplied ID's and the table
is identified by the table_class.

Rich text editing


By adding 'Rich text'-extension to the report from report parameters, one can use 'richtext' editing type which
will bring up full fledged editor. The editor can be invoked from direct HTML code or from HTML code shown
with dbr.html:.

myDBR uses TinyMCE for the Rich Text editor. TinyMCE options can be passed in in as the 'richtext'-option.

To show the HTML code as rendered HTML, we'll use 'dbr.html:' in the query. To enable rich text editing, we'll
use 'type=richtext' and use option "'html':1" to indicate that we'll be converting the HTML into editable format.

select 'dbr.editable', 'rich_text', 'sp_DBR_edit_rich_text', 'in_id=id', 'type=richtext',


"options={'html':1,'richtext':{'width': 600, 'height': 350}}";
select 'dbr.hidecolumn', 'id';
select 'dbr.colstyle', 'rich_text', '[white-space: pre;]';

218
Commands

select id, concat('dbr.html:', rich_text) as rich_text


from rich_text;

219
Commands

One can also use direct HTML code to invoke the editor. In this case the code is shown as is in the query and
no html-option is passed.

select 'dbr.colstyle', 'rich_text', '[white-space:pre]';


select 'dbr.hidecolumn', 'id';
select 'dbr.editable', 'rich_text', 'sp_DBR_edit_rich_text', 'in_id=id', 'type=richtext',
"options={'richtext':{'width': 600, 'height': 350}}";

select id, rich_text


from rich_text;

220
Commands

Code editing

By adding 'Code editor'-extension to the report from report parameters, one can use code editing with 'html',
'php', 'javascript', 'css' and 'sql' types.

select 'dbr.hidecolumn', 'id';


select 'dbr.editable', 'code', 'sp_DBR_edit_code', 'inA=id', 'type=php';
select 'dbr.colstyle', 'code', '[white-space:pre;font-family:Courier]';

select id, code


from code_editing;

221
Commands

Example of using dbr.upload


With dbr.upload, one can offer file upload capability to the server.

select 'dbr.upload.options', 'noreplace', 1;


select 'dbr.upload.options', 'accepted_files', '.pdf,.xlsx';

select 'dbr.upload', '/var/www/upload', 'sp_DBR_upload_file', v_client_id;

select 'dummy';

The upload procedure takes three fixed parameters path, filename and file size. One can also pass additional
parameters to the proceudre. The procedure will return the text that is shown to the user after successful upload.

create procedure sp_DBR_upload_file(


in_path varchar(255),
in_file varchar(255),
in_size int,
in_id int,
inLogin varchar(30)
)
begin

insert into uploads


values (inLogin, in_path, in_file, in_size, in_id, now());

select concat('File ', in_file, ' uploaded (',format_bytes(in_size),')');

end

222
Commands

Passing HTML into the page


Commands

dbr.html - Pass HTML directly into the report


dbr.purehtml - Same as dbr.html, kept for compatibility
dbr.html: - Include HTML into a string
dbr.purehtml: - Same as dbr.html:, kept for compatibility
dbr.javascript - Include Javascript code in the report
dbr.css - Include CSS definitions in the report
dbr.head - Include tags into HTML head part

Syntax

select 'dbr.html', 'HTML statement'


select 'dbr.purehtml', 'HTML statement'
select 'dbr.html:HTML statement'
select 'dbr.purehtml:HTML statement'
select 'dbr.javascript', 'javascript code' [, 'onload']
select 'dbr.css', 'css'
select 'dbr.head', html_tags

Explanation

By default myDBR will show any HTML-commands that may be selected within the data as a raw code without
letting the browser to render it. With these commands, myDBR allows the browser render the selected HTML-
code.

With the dbr.html-command you can allow client browser to render the HTML. The dbr.html-command
makes the whole result set to be passed directly to the browser, as with the dbr.html:-syntax this allows
mixing HTML within the query. The dbr.html: allows HTML formatting inside the result table's cell.

You can also pass Javascript code with 'dbr.javascript'. The command is a short version of 'dbr.html' and adds
script tags around the parameter. The optional 'onload'-parameter makes the script to run after the DOM-tree
has been loaded Adding your own CSS can be done with 'dbr.css' which works similarly.

This allows the report author to include any content in the report and also to affect the layout of the report.

Example - dbr.html

Putting a logo in the left top corner of the report. Embed Google Maps map and YouTube video side by side
in a report.

select 'dbr.title', ''; /* We do not need the title */

/* Putting up the logo. We'll use a predefined left div */


select 'dbr.html', '<div class="left"><img src="http://mydbr.nocsos.com/images/nocsos-
logo.png"></div>';

/* Use this as title */


select 'dbr.hideheader';
select 'BMW F1 vs, BMW M5';

/* Put map and video side by side. 1st column */


select 'dbr.html', '<table align="center"><tr><td>';

223
Commands

select 'dbr.hideheader';
select 'Google map: Rockingham Race Track';

/* We have the Google Map URL here */


select 'dbr.html', RockinghamURL
from mydb.Racetracks;

/* 2nd column */
select 'dbr.html', '</td><td>';

select 'dbr.hideheader';
select 'Video: Fifth Gear';

/* We have the YouTube video URL here */


select 'dbr.html', F1vsM5URL
from mydb.Videos;

/* Close the table */


select 'dbr.html', '</td></tr></table>';

Report will position the logo on top left. Map and video will appear side-by-side:

Example - 'dbr.html:'
The report will output a list of parts and their picture.

select 'Part 1' as 'Part name',


'WDC-2345-1' as 'Code',
'dbr.html:<img src="http://www.mysite.com/parts/WDC-2345-1.jpg">' as 'Preview'
union
select 'Part 2',
'WDC-2345-2',
'dbr.html:<img src="http://www.mysite.com/parts/WDC-2345-2.jpg">'
union
select 'Part 3',
'WDC-2345-3',
'dbr.html:<img src="http://www.mysite.com/parts/WDC-2345-3.jpg">';

224
Commands

The report will output a normal myDBR report list. myDBR will just put the indicated picture in the third column's
cell.

Example - 'dbr.head'

You can include your own tags into HTML HEAD section with dbr.head

select 'dbr.head', '<meta property="og:url" content="http://mydomain.com/index.htm">';


select 'dbr.head', '<meta name="twitter:card" content="summary_large_image">';
select 'dbr.head', '<meta name="twitter:card" content="summary_small_image">';

The report will output a normal myDBR report list. myDBR will just put the indicated picture in the third column's
cell.

Templates
Commands

dbr.template - Defines a template being used for the subsequent result set

Syntax

select 'dbr.template', '#template' | 'row template code' | 'header template code', 'row
template code', 'footer template code', [ 'template_class' | 'none' ]

Explanation

By using a template, you can fully define the result set formatting. A template is an HTML code which can contain
any valid HTML code including CSS and JavaScript.

A template consist of three sections: header, row and the footer. The header-section is applied before any data
is processed, the row-section is repeated for each result set row and the footer-section is applied after the data
is processed.

A template section can contain myDBR localization references (like #{title}). The parameter to dbr.template-
command can be a reference to a stored template (syntax: {#template}, syntax #template kept for compatibility),
all three template sections, or just the row-section.

225
Commands

The row-template code can contain template variables, which will be replaced by the result set data for each
row. The syntax of the reference is '#ColumnRef', where the ColumnRef is the column reference in the result
set. Template variables cannot be used in header- or in footer-sections.

A template variable can also be replaced with a full myDBR result set. To do this, first record a result set using
'dbr.record' command with the template variable as a parameter. Next template used will use the recorded result
set as a value of the template variable.

The template will be, by default, enclodes in a DIV with class 'template'. An additional template class can be
added

Examples
Simple square

We'll create a template that will show data in squares. The color of the square is determined by the report.

First we'll create a template row called 'square' which contains a CSS style and a DIV. The template contains
two parameters #title for the square text and #color to be used in the CSS style.

<style>
.mycenter_div {
vertical-align: middle;
text-align: center;
width:70px;
height:70px;
line-height: 70px;
border:1px solid gray;
margin: 5px;
display: inline-block;
box-shadow: 10px 10px 5px #888;
}
</style>

<div class="mycenter_div" style="background-color:#color">{#title}</div>

The actual report calls the template and makes the query:

create procedure sp_DBR_Template()


begin

select 'dbr.template', '#square';

select title, color


from mydb.data;

end

And the output of the report will show the squares:

226
Commands

You could make the squares movable by adding a call to jQuery in the template's footer code

<script>$(function() { $( ".mycenter_div" ).draggable().css('cursor','pointer'); });</


script>

An invoice form

We'll create an invoice form which contains three templates. an invoice header, invoice rows and invoice footer.

The invoice header is an HTML table which will contain the basic invoice data. The table can be put fully into
the template row as the result set contains only one row:

<table style="margin-top: 40px;margin-bottom: 30px">


<tr>
<td rowspan=3>
<img style="height:60px" src="http://mydbr.com/demo/mydbr/images/apppic.png" />
</td>
<td style="padding-left:10px" rowspan=3>
<span style="font-size:2em">{#company}</span><br />
#address
</td>
<td colspan=3>&nbsp;</td>
</tr>

<tr>
<td style="width:220px"></td>
<td style="text-align:right"><b>#{DATE}:</b></td>
<td style="text-align:right">{#date}</td>
</tr>

<tr style="vertical-align: top;">


<td style="width:220px"></td>
<td style="text-align:right"><b>#{INVOICE} #:</b></td>
<td style="text-align:right">{#invoice_nbr}</td>
</tr>
</table>

The invoice rows will be printed also as an HTML table. Now that there will be multiple rows in the result set,
we'll separate table rows from the header and footer.

The invoice row's template header contains the column titles. In the example the titles are localized using
myDBR's localization syntax. The invoice rows are formatted using CSS.

Invoice rows template header:

<style>
.inv_rows { border: 1px solid #555; border-collapse: collapse }
.inv_rows th { background-color: #E0E0E0; border-bottom: 1px solid #555 }
.inv_rows th, .inv_rows td { padding: 5px }
.inv_rows th.right, .inv_rows td.right { text-align: right }
.inv_rows th.left, .inv_rows td.left { text-align: left }
</style>

<table class="inv_rows">
<thead>
<tr>
<th class="left" style="width: 40px">ID</th>

227
Commands

<th class="left" style="width: 320px">Name</th>


<th class="right" style="width: 80px">Quantity</th>
<th class="right" style="width: 80px">Unit price</th>
<th class="right" style="width: 80px">Total</th>
</tr>
<thead>

The invoice rows template row contains definitions for each row in the result set. Values to be replaced with
result set content are prefixed with '#'.

<tr class="#alternate_row_color">
<td>{#id}</td>
<td class="left">{#title}</td>
<td class="right">{#quantity}</td>
<td class="right">{#unitprice}</td>
<td class="right">{#total}</td>
</tr>

The invoice row's template footer just closes the created table:

</table>

The invoice footer is just one row in the result set and therefore we can define it as one template row-section:

<table class="inv_rows" style="border-top:none">


<tr>
<td style="width: 40px"></td>
<td style="width: 320px"></td>
<td style="width: 80px"></td>
<td class="right" style="width: 80px">#{SUBTOTAL}</td>
<td class="right" style="width: 80px">{#total_rows}</td>
</tr>
<tr>
<td style="width: 40px"></td>
<td style="width: 320px"></td>
<td class="right" style="width: 80px">#{VAT}</td>
<td class="right" style="width: 80px">{#vat_percent}</td>
<td class="right" >{#vat_eur}</td>
</tr>
<tr>
<td style="width: 40px"></td>
<td style="width: 320px"></td>
<td style="width: 80px"></td>
<td class="right" style="width: 80px"><b>#{TOTAL}</b></td>
<td class="right" style="width: 80px">{#total}</td>
</tr>
</table>

The actual report contains queries for each template

create procedure sp_DBR_invoice(


in_invoice_id int
)
begin

228
Commands

select 'dbr.template', '#square';

select 'dbr.title', '';

select 'dbr.template', '#invoice_header';

select name as 'company',


address as 'address',
invoice_date as 'date',
invoice_number as 'invoice_nbr'
from mydb.invoice
where invoice_id=in_invoice_id;

select 'dbr.template', '#invoice_rows';

select rowid as 'id',


title as 'title',
quantity as 'quantity',
unit_price as 'unitprice',
quantity * unit_price as 'total',
'dbr.rownum%2 ? "odd" : "even"' as 'alternate_row_color'
from mydb.invoice_rows
where invoice_id=in_invoice_id
oder by rowid;

select 'dbr.template', '#invoice_footer';

select 'dbr.colstyle', 'vat_percent', '%d %';


select 'dbr.colstyle', 'total_rows', '%.2f €';
select 'dbr.colstyle', 'vat_eur', '%.2f €';
select 'dbr.colstyle', 'total', '%.2f €';

select total_net as 'total_rows',


vat_percent as 'vat_percent',
vat as 'vat_eur',
total_net+vat as 'total'
from mydb.invoice
where invoice_id=in_invoice_id;

end

The final result is the invoice form

229
Commands

Using full queries inside a template


We'll create a report that will create a single table using multiple templates. Each template constructs a separate
element inside the table.

The report uses two normal myDBR querirs and insert's a template between the queries and creates a single
report object.

We'll create a template that will create a row in the template containing a single text.

<tr>
<td colspan="7" style="padding:15px;text-align:center;border:1px solid
#DDDDDD;background:#FFFCC9">{#text}</td>
</tr>

create procedure sp_DBR_Template()


begin

select 'dbr.crosstab', 'Quarter';


select 'dbr.sum', 'Items', 'Weight';
select 'dbr.hsum', 'Items', 'Weight';

-- Do not create the footer/close the table) for the table as we will add more rows
select 'dbr.resultset.options', 'skip_footer';

select
Name,

230
Commands

concat(year(InsertDate), ' Q',quarter(InsertDate)) as 'Quarter',


sum(Items) as 'Items',
sum(Weight) as 'Weight'
from TestTable
where quarter(InsertDate)=1 and Name<'Cordex'
group by Name, concat(year(InsertDate), ' Q', quarter(InsertDate))
order by Name;

-- Insert a template row. Do not enclude template into a div ('none') as it will part of a
table
select 'dbr.template', '#row_insert', 'none';
select 'This is the text in the middle' as 'text';

-- The rest of the table. We do not need header as is is already created


select 'dbr.resultset.options', 'skip_header';

select 'dbr.crosstab', 'Quarter';


select 'dbr.sum', 'Items', 'Weight';
select 'dbr.hsum', 'Items', 'Weight';

select
Name,
concat(year(InsertDate), ' Q',quarter(InsertDate)) as 'Quarter',
sum(Items) as 'Items',
sum(Weight) as 'Weight'
from TestTable
where quarter(InsertDate)=1 and Name>='Cordex'
group by Name, concat(year(InsertDate), ' Q', quarter(InsertDate))
order by Name;

end

And the output of the report will show a single table:

231
Commands

Recording template variables


You can also record full report sections using dbr.record and use the recorded report elements as template
variables. The second parameter for dbr.record command is the template variable where the query result is
stored.

We'll create a template "bi_box" that will be a dashboard element

<div class="bi_box {#bi_width}">


<div class="bi_header {#bi_width}">
<div class="bi_header1">{#bi_header1}</div>
<div class="bi_header2">{#bi_header2}</div>
</div>
<div class="bi_data {#bi_width} {#bi_dheight}">
<div class="bi_green {#bi_show_green}"><div class="bi_green_data">{#bi_green}</
div></div>
{#bi_content}
</div>
</div>

The report will use the template using a template variable with custom CSS.

create procedure sp_DBR_dasboard()


begin

select 'dbr.css', '


body { background: #efefef}

.dashboard {
display: flex;
flex-wrap: wrap;
justify-content: flex-start;
justify-content: center;
margin-top: 20px;
}

.bi_box { text-align: left; margin-left: 10px; margin-top: 10px; box-shadow: 2px 2px 3px
0px #CCC; }
.bi_box.narrow, .bi_box .bi_data.narrow { width: 220px; }
.bi_header, .bi_data { background: white; border: 1px solid #CCC; padding: 10px; }
.bi_data { display: table-cell; vertical-align: bottom; }
.bi_header1 { color: black; font-weight: bold; font-size: 1.3em}
.bi_header2 { color: gray; padding-top: 3px }
.bi_box .small { height: 100px }
.bi_box .text { font-size: 40px; text-align: center;line-height: 80px }
.bi_box .rstable {margin-bottom: 0px;}
.bi_green_data { font-size: 24px; color: green; text-align: right; line-height: 16px}
.bi_green.no { display:none}
';

-- Wrap the dashboard elements in a flex-div


select 'dbr.html', '<div class="dashboard">';

-- Start the recording. Following query will be put into the bi_content-variable

select 'dbr.record', 'begin', 'bi_content';

select 'dbr.chart', 'column', '', 190, 90;


select 'dbr.chart.options','padding_right', -30;
select 'dbr.chart.options','padding_left', -3;

232
Commands

select month, value


from mydata;

-- End the recording. The chart is now in the bi_content-variable


select 'dbr.record', 'end';

-- Use the template


select 'dbr.template', '#bi_box';

-- Pass oher variables to the template


select
'narrow' as 'bi_width',
'Execution effiency' as 'bi_header1',
'By Score' as 'bi_header2',
'small' as 'bi_dheight',
null as 'bi_green',
'no' as 'bi_show_green';

-- Do the second dashboard element


select 'dbr.template', '#bi_box';
select 'dbr.colstyle', 'bi_content', '$%.2fM';
select 'dbr.colstyle', 'bi_green', '+$%.1f%';

select
revenue as 'bi_content',
growth_percent as 'bi_green',
'narrow' as 'bi_width',
'Expected Revenue' as 'bi_header1',
'This year' as 'bi_header2',
'small text' as 'bi_dheight',
'yes' as 'bi_show_green'
from mydata;

select 'dbr.html', '</div>';

end

The report will show two dashboard elements

Running total
Commands
dbr.running_total - Calculate running total for a column

233
Commands

Syntax

select 'dbr.running_total', ColumnRef [, SourceColumnRef ]

Explanation

A running total is the sum of any given column that is incremented/decremented row by row.

The command has two options. When only one parameter is given, the running total is calculated over the
column given. If the second parameter is given, the column in the first parameter gets the running total of the
second column's value. The running total can be used both in tabular reports and in charts.

Examples

Using running total in tabular report

A 'Running total' is a column that is calculated from the column itself and 'Running total 2' is a column that is
calculated from 'Revenue'-column

select 'dbr.running_total', 'Running total';


select 'dbr.running_total', 'Running total 2', 'Revenue';

select
revenue_month as 'Month',
revenue as 'Revenue',
revenue as 'Running total',
null as 'Running total 2'
from mydb.data;

Using a running total in a chart

Drawing a cumulative revenue chart

select 'dbr.chart', 'line', 'Cumulative Revenue';


select 'dbr.running_total', 'Revenue';

select
revenue_month as 'Month',
revenue as 'Revenue'
from mydb.data;

234
Commands

Import commands

myDBR allows data to be imported from a local file or from a remote file. The import process reads the file
and processes it row by row with a given import report. You can make preparations before and after the import
process. The imported file can be a tab delimited file, a CSV file, a JSON file or a XLSX Excel file (local only).

Commands
dbr.import.prepare - Before the import is done, this preparation report is run
dbr.import.finish - After the import is finished, this report is run
dbr.import - This procedure is called for each import row
dbr.import.options - Set import options

Syntax

select 'dbr.import.prepare', prepare_procedure


select 'dbr.import.finish', finish_procedure
select 'dbr.import', import_procedure [, remote_url [, 'now']]
select 'dbr.import.options', 'option', value

Where:

prepare_procedure The name of the stored procedure to be called before the import is initiated

finish_procedure The name of the stored procedure to be called after the import is done

import_procedure An import procedure which handles the import rows. myDBR will automatically read
report parameters and match the parameters to input file's columns

remote_url If the file to be imported is a URL pass it here. If not specified a local file is asked
from user

235
Commands

'now' If specified no user input is required to initiate the import

Options:

• skip_header - defines number of header lines to skip in import

• extra_columns - allows pass constant to import procedure (first parameters)

• charset - allows define import files chartset (will be converted to UTF-8)

• format 'tab' | 'json' | 'csv' | 'xlsx' - import format file type: 'tab' (tab delimited) or 'json' (JSON), 'xlsx' (Excel)

• title - title text for the import dialog

• button.text - Import-button text

• csv_delimiter - CSV delimiter for the import, default = ,

• csv_enclosure - CSV enclosure for the import, default = "

• line_ending 'cr' - Line ending for the file default = chr(10)

Sample import
We have a table into which we wish to import data from Excel spreadsheet. The table definition looks like this:

create table parts (


id int,
name varchar(30),
creation_date date,
primary key(id)
)

The Excel sheet has the same columns with additional header:

We'll create an import report which will ask user to select the local file and it will import the data to the table.

create procedure sp_DBR_my_import()


begin

/* Skip one header line from the Excel file */


select 'dbr.import.options', 'skip_header', 1;
/* Tell that we are importing an Excel file */
select 'dbr.import.options', 'format', 'xlsx';

/* Define the import report which will do the actual import */


select 'dbr.import', 'sp_DBR_import_do';

end

236
Commands

The next thing that we need to do, is to create the sp_DBR_import_do -report and add it to the myDBR as report.
User needs to have access rights to the report in order to run the import. The report has the same columns
(column names/parameter names do not matter) in same order.

create procedure sp_DBR_import_do(


inID int,
inName varchar(30),
inDate date
)
begin

insert into mydata.parts (id, name, creation_date)


values ( inID, inName, inDate );

end

When the sp_DBR_my_import -report is run, myDBR will ask user the file to be imported and then call the
sp_DBR_import_do report against each of the rows in the Excel-file with parameters from the Excel file's row.

Import from a remote JSON source without user action


We have a remote sevice serving JSON which we wish to import. Before the import, a preparation report
sp_DBR_import_begin is called. After the import is finished, the sp_DBR_import_end-report is called.

If we include 'now' as a last parameter, no user interaction is required to invoke the import and the import is
run as soon as the report is run.

select 'dbr.import.prepare', 'sp_DBR_import_begin';


select 'dbr.import.finish', 'sp_DBR_import_end';
select 'dbr.import.options', 'format', 'json';

select 'dbr.import', 'sp_DBR_import_do' ,'http://myservice.com/index.php?serviceID=5',


'now';

import_procedure
The import procedure should have the same number of parameters as the input file has tab separated columns.
For example if we have a text file consisting of three columns (\t is a tab character in the file), we would have
an import file and an import_procedure that would look like this:

201\tCar\t2011-09-12
202\tSink\t2011-10-22

Import with constants


You can pass constants to the import procedure. The constants are passed as first parameters and are defined
with the extra_columns-option

select 'dbr.import', 'sp_DBR_import_do';

We have a remote file which we wish to import. Before the import a preparation report is called. After the import
is finished, a report is called. No user interaction is required to invoke the import

select 'dbr.import.options', 'skip_header', 1; /* Treat first line as header and skip it


*/

237
Commands

select 'dbr.import.options', 'extra_columns', 10; /* Pass constant 10 as first parameter


to 'sp_DBR_import_do', rest of the parameters come from import file */
select 'dbr.import', 'sp_DBR_import_do';

Additional UI functionality after import is done


The dbr.import.finish-routine can also return JavaScript to the main import routine to trigger additional
functionality. This can for example be utilized to show the imported data.

select 'dbr.import.finish', 'sp_DBR_import_end';


select 'dbr.import', 'sp_DBR_import_do';

select 'dbr.button', 'Show import result', 'invisible import_result';


select 'dbr.report', 'sp_DBR_import_show_result', 'results_div[]';

select 'dummy';

create procedure sp_DBR_import_end()


begin

-- Click the 'Show import result' button once import is done


select concat('dbr.html:Import done<script>$(".import_result")[0].click();</script>');

end

Export commands

myDBR allows report data to be exported to various formats: Excel, PDF, CSV, JSON and php serialized. Export
options exists for extra functionality for the exports.

Exporting a report requires adding '&export=format' to the URL. Supported export formats are:

• xls - Excel format (old)

• xlsx - Excel format (new). Requires zip support in PHP.

• pdf - Portable Document Format (PDF). Can either use built in PDF export or external and more complete
wkhtmltopdf.

• csv - CSV format

• json - the result is delivered as a JSON. If the report contains multiple result sets, the resulting array is a
multidimensional JSON. Only basic result sets are supported (no support for charts, cross tables etc). This
export-format is meant for exchanging data between systems.

• xml - the result is delivered as xml. Only basic result sets are supported (no support for charts, cross tables
etc). This export-format is meant for exchanging data between systems.

• sql - the result is delivered as sql-commands. One can optionally skip the myDBR commands adding
parameter '&skip_mydbr_cmds=1' to the url.

• php_serialized - the result is delivered as a serialized php-array. Only basic result sets are supported (no
support for charts, cross tables etc). This export-format is meant for exchanging data between systems.

For JSON data, additional URL parameters can be used to define the JSON format used.

• default - json array

238
Commands

• &json_force_object=1 - json object

• &json_object_array=1 - json object array

Commands
dbr.export.options - Set export option
dbr.wkhtmltopdf - Pass command line parameters to wkhtmltopdf command
dbr.calc.excel - Define an Excel native formula for a column
dbr.blob - Read file from database

Syntax

select 'dbr.export.options', option, value


select 'dbr.wkhtmltopdf', command_line_parameters
select 'dbr.calc.excel', ColumnReference, excel_formula
select 'dbr.blob', file_extension, filename

Export options

• orientation - Set page orientation ('landscape', 'portrait') in PDF and Excel. Use this in first result set only.
Export document can have only one orientation.

• paper_size - Set page size PDF and Excel. See list below for different options.

• zoom_scale - Set Excel zoom scale (value 50 is 50% zoom).

• gridlines - Disable/enable Excel gridlines

• font - Set font used in Excel.

• font_size - Set font size in pixels used in Excel.

• font_width - PDF output approximates the character width when auto sizing cells. You can adjust the cell
width with this option.

• autosize - Turn Excel autosize on / off. Will try to fit the output into a cell.

• pagebreak - Will produce a page break in PDF.

• worksheet - Will create a new worksheet with a given name (value) in Excel

• position - Will place the object into a given position. Example position is "C6".

• disable - Disable chosen export types. Will get comma separated list of disabled export types (pdf,excel)

• debug - Will display wkhtmltopdf command and the generated HTML file for debugging possible errors in
user generated HTML as wkhtmltopdf may fail to produce PDF from erroneous HTML

• header.title - Define PDF export header title

• header.title.style - Define PDF export header title CSS style

• include_image - Defines whether charts are included in the Excel export

• csv.delimiter - Allows setting a CSV delimiter on a per report basis

• csv.decimal_point - Allows setting a CSV decimal_point on a per report basis

• csv.enclosure - Allows setting a CSV enclosure on a per report basis

239
Commands

• csv.date_format - Allows setting a CSV date_format on a per report basis

• csv.time_format - Allows setting a set CSV time_format on a per report basis

• csv.charset - Allows setting CSV charset on a per report basis

• csv.line_ending - Allows setting CSV line_ending on a per report basis

• csv.header - Allows setting CSV header visibility on a per report basis

• csv.enclose_string_with_leading_or_trailing_space - Allows setting CSV export quotes strings with leading


or trailing_space

• csv.linefeed_between_resultsets - If report contains multiple result sets, this will determine if the result sets
are separated with linefeed

• csv.use_bom_in_utf - Use BOM (Byte order mark) in the CSV file

• csv.direct_mode - If the export report contains just one large result set, direct_mode can be used to speed
up the export

• csv.skip_formatting - Ignore column formatting in CSV export

• csv.strip_tags - Strip tags in csv export

• excel.aggregate_formula, 1/0 - Enable/disable Excel native formulas in aggregate summary rows

• xml.declaration - Define the XML declaration

• xml.header - Define additional header tags

• xml.root_tag - Defines the XML root tag. If not defined, a generic "report" is used

• xml.tag_attributes comma_separated_colreflist - Turns values to data attributes. The parameter is a comma


separated list of column references

• xml.compatibility_mode, 1 - Use old, pre myDBR 4.0, XML format

• filename - define the export file within the report

• colwidths - Define an Excel column widths in pixels

• formula - Define an Excel formula in a cell. Format: 'formula:A2'[, 'colsyle'] or 'formula:ColumnReference'[,


'colsyle']

• position.row row - Set Excel export row for result set (select 'dbr.export.options', 'position.row', 1;)

• position.column Column - Set Excel export column for result set (select 'dbr.export.options',
'position.column', 'E';)

• position.row.add nbr_of_rows - Move result set nbr_of_rows-rows lower (select 'dbr.export.options',


'position.row.add', 3;)

• position.column.add nbr_of_columns - Move result set nbr_of_column-columns to right (select


'dbr.export.options', 'position.column.add', 2;)

• tab_title.hide - Do not show tab titles in Excel export. Use this in first result set only.

See also defaults.php for more options.

Available page sizes for PDF (wkhtmltopdf) export:

• A0 (841 x 1189 mm)

240
Commands

• A1 (594 x 841 mm)

• A2 (420 x 594 mm)

• A3 (297 x 420 mm)

• A4 (210 x 297 mm, 8.26 x 11.69 inches)

• A5 (148 x 210 mm)

• A6 (105 x 148 mm)

• A7 (74 x 105 mm)

• A8 (52 x 74 mm)

• A9 (37 x 52 mm)

• B0 (1000 x 1414 mm)

• B1 (707 x 1000 mm)

• B2 (500 x 707 mm)

• B3 (353 x 500 mm)

• B4 (250 x 353 mm)

• B5 (176 x 250 mm, 6.93 x 9.84 inches)

• B6 (125 x 176 mm)

• B7 (88 x 125 mm)

• B8 (62 x 88 mm)

• B9 (33 x 62 mm)

• B10 (31 x 44 mm)

• C5E (163 x 229 mm)

• Comm10E (105 x 241 mm, U.S. Common 10 Envelope)

• DLE (110 x 220 mm)

• Executive (7.5 x 10 inches, 190.5 x 254 mm)

• Folio (210 x 330 mm)

• Ledger (431.8 x 279.4 mm)

• Legal (8.5 x 14 inches, 215.9 x 355.6 mm)

• Letter (8.5 x 11 inches, 215.9 x 279.4 mm)

• Tabloid (279.4 x 431.8 mm)

Note that you can also use wkhtmltopdf options --page-height and --page-width to define a custom page size.

Available page sizes for Excel export:

• 6_3_4_ENVELOPE

241
Commands

• A2_PAPER

• A3

• A3_EXTRA_PAPER

• A3_EXTRA_TRANSVERSE_PAPER

• A3_TRANSVERSE_PAPER

• A4

• A4_EXTRA_PAPER

• A4_PLUS_PAPER

• A4_SMALL

• A4_TRANSVERSE_PAPER

• A5

• A5_EXTRA_PAPER

• A5_TRANSVERSE_PAPER

• B4

• B4_ENVELOPE

• B5

• B5_ENVELOPE

• B6_ENVELOPE

• C3_ENVELOPE

• C4_ENVELOPE

• C5_ENVELOPE

• C65_ENVELOPE

• C6_ENVELOPE

• C

• D

• DL_ENVELOPE

• E

• EXECUTIVE

• FOLIO

• GERMAN_LEGAL_FANFOLD

• GERMAN_STANDARD_FANFOLD

• INVITE_ENVELOPE

242
Commands

• ISO_B4

• ISO_B5_EXTRA_PAPER

• ITALY_ENVELOPE

• JAPANESE_DOUBLE_POSTCARD

• JIS_B5_TRANSVERSE_PAPER

• LEDGER

• LEGAL

• LEGAL_EXTRA_PAPER

• LETTER

• LETTER_EXTRA_PAPER

• LETTER_EXTRA_TRANSVERSE_PAPER

• LETTER_PLUS_PAPER

• LETTER_SMALL

• LETTER_TRANSVERSE_PAPER

• MONARCH_ENVELOPE

• NO10_ENVELOPE

• NO11_ENVELOPE

• NO12_ENVELOPE

• NO14_ENVELOPE

• NO9_ENVELOPE

• NOTE

• QUARTO

• STANDARD_1

• STANDARD_2

• STANDARD_PAPER_1

• STANDARD_PAPER_2

• STANDARD_PAPER_3

• STATEMENT

• SUPERA_SUPERA_A4_PAPER

• SUPERB_SUPERB_A3_PAPER

• TABLOID

• TABLOID_EXTRA_PAPER

243
Commands

• US_STANDARD_FANFOLD

PDF export with built in PDF export and with wkhtmltopdf


myDBR supports wkhtmltopdf if installed on the server. wkhtmltopdf uses the Webkit rendering engine to convert
content to PDF. Please see Optional installations on how to install wkhtmltopdf into your server.

When wkhtmltopdf is installed, PDF exports will support all html and javascript code generated (even with
dbr.html).

By default, wkhtmltopdf export uses the header defined by the mydbr/user/export_header.php as '--header-html'
option in wkhtmltopdf. If this option is overridden with a parameter to 'dbr.wkhtmltopdf', a defined export header
will be used. If you leave the '--header-html' -option as empty, no header is used.

Examples
We have our data set:

select 'dbr.export.options', 'orientation', 'landscape';


select 'dbr.export.options', 'paper_size', 'A3_EXTRA_PAPER';
select 'dbr.export.options', 'zoom_scale', 50;
select 'dbr.export.options', 'font', 'Verdana';
select 'dbr.export.options', 'font_size', 11;
select 'dbr.export.options', 'autosize', 0; /* Turn off autosize */
select 'dbr.export.options', 'pagebreak', 1;
select 'dbr.export.options', 'disable', 'pdf,excel';
select 'dbr.wkhtmltopdf', "--header-html ''"; /* Do not use header in export using
wkhtmltopdf */

Excel calculation
You can use Excel calculations in Excel export.

select 'dbr.calc', 'total', '[A]*[B]';


select 'dbr.calc.excel', 'total',
'=indirect(address(row(),column()-2))*indirect(address(row(),column()-1))';

select 10 as 'A', 20 as 'B', null as 'total';

Memory usage for export


The export feature uses more memory that the rest of the application. If you run into problems with export
functionality, try to increase the 'memory_limit'-parameter in php.ini. See the error message about required
memory.

XML export
The generated XML file will include all the result sets of the query. An example XML report and output:

select 'dbr.export.options', 'xml.declaration', '<?xml version="1.0" encoding="utf-8"?>';


select 'dbr.export.options', 'xml.header', '<publisher>myDBR System<publisher>';
select 'dbr.export.options', 'xml.root_tag', 'dataroot xmlns:od="urn:schemas-
microsoft-com:officedata" xmlns:xsi="http://www.w3.org/2000/10/XMLSchema-instance"
xsi:noNamespaceSchemaLocation="filmlist.xsd"';

/* Will define the result set name in XML */


select 'dbr.resultclass', 'films';

244
Commands

/* Use these two columns as attributes */


select 'dbr.export.options', 'xml.tag_attributes', 'id', 'release_year';
/* Name the row in XML */
select 'dbr.rowclass', 'rowclass';
/* Do not show the rowname as data */
select 'dbr.hidecolumn', 'rowclass';

select
film_id as 'id',
title as 'Title[filmtitle]',
description,
release_year,
last_update,
'film' as 'rowclass'
from mydata.film;

You can define the result set's name with the dbr.subtitle-command. If none is given, myDBR will generate
one. Column attribute names and datatypes are defined by the report. In the example the column name 'title'
has been changed to 'filmtitle'.

<?xml version="1.0" encoding="utf-8"?>


<publisher>myDBR System<publisher>
<dataroot xmlns:od="urn:schemas-microsoft-com:officedata" xmlns:xsi="http://
www.w3.org/2000/10/XMLSchema-instance" xsi:noNamespaceSchemaLocation="filmlist.xsd">
<film id="1" release_year="2006">
<filmtitle>ACADEMY DINOSAUR</filmtitle>
<description>
A Epic Drama of a Feminist And a Mad Scientist who must Battle a Teacher in The
Canadian Rockeless
</description>
<last_update>2010-08-18T10:22:10</last_update>
</film>
<film id="2" release_year="2007">
<filmtitle>AMERICAN BACON</filmtitle>
<description>Newly released film</description>
<last_update>2010-09-23T15:22:55</last_update>
</film>
</dataroot>

JSON formats
By default myDBR uses JSON array as JSON format. You can use change the default format with extra URL
parameters json_force_object and json_object_array.

With report:

select film_id, title, release_year


from film f
limit 0,2;

The default JSON export format is a JSON array:

[
[
1,
"ALAMO VIDEOTAPE",
2006
],

245
Commands

[
1,
"ALASKA PHANTOM",
2006
]
]

With &json_object_array=1 is added to the URL, the format is JSON object format:

{
"0": {
"film_id":1,
"title":"ALAMO VIDEOTAPE",
"release_year":2006
},
"1": {
"film_id":2,
"title":"ALASKA PHANTOM",
"release_year":2006
}
}

With &json_force_object=1 is added to the URL, the format is JSON object array format:

[
{
"film_id":1,
"title":"ALAMO VIDEOTAPE",
"release_year":2006
},
{
"film_id":2,
"title":"ALASKA PHANTOM",
"release_year":2006
}
]

Excel formula
With formula-option you can add an Excel-formula into a cell for exports. Commmand accepts both direct cell
refences or it can be attached to existing query column via ColumnReference.

Direct cell reference formula takes a Excel cell reference as parameter and a formula to calculate. Optional
columstyle can be used.

select 'dbr.export.options', 'formula:A10','=A5*2', '# ##0';

With ColumnReference a calculation can be added to an existing result set.

/* For Excel output */


select 'dbr.export.options', 'formula:
[Calculated]','=INDIRECT(ADDRESS(ROW(),COLUMN()-1))*2', '# ##0';

/* For HTML output */


select 'dbr.calc', 'Calculated', '[value]*2';

select ID, value, null as 'Calculated';

246
Commands

from mydata;

Reading files from database


With dbr.blob you can read files stored in blob/varbinary column.

select 'dbr.blob', 'pdf', 'document.pdf';

select data
from document_blob
where type='pdf';

Remote calls to other myDBR servers

myDBR installation can make queries to other myDBR installations. This allows reports to combine data from
multiple databases even if the databases are not connected to each other.

Commands
dbr.remote.prepare - Defines the server to be called, call to be made and local table to receive the results.
Required, needs to be called before 'dbr.remote.call'
dbr.remote.call - Executes the defined remote call and runs local report to handle the results. Required.
dbr.remote.options - Allows setting extra options for transfer. Option includes to turn off certificate check
on remote server. Optional and needs to be called before 'dbr.remote.prepare'.

Syntax

select 'dbr.remote.prepare', 'server', 'localtable', remote_report[,


remote_report_parameters]
select 'dbr.remote.call', 'local_report'[, local_report_parameters]
select 'dbr.remote.options', 'option'[, value]

Where:

247
Commands

server The nickname for the remote server defined in 'Remote servers'

localtable Local table to receive the results (can be a temporary table). The format of
the table must match the output of the remote report call

remote_report / Remote server's myDBR report's stored procedure name with parameters
remote_report_parameters

local_report The local report to be called after the remote report is run and put into local
table.

local_report_parameters Comma separated list of parameters for local report

Options include:

skip_ssl_verify If set myDBR will connect to remote server even if the SSL certificate is
invalid.

use_proxy When a proxy server is defined in myDBR environmental settings, this setting
defines whether to use it or not.

use_local_authentication If set myDBR will use local authentication with remote calls. For example if
myDBR is set to use LDAP authentication, this would allow remote calls to
use myDBR's own authentication.

timeout How long will the local server wait for the remote server. The default is
defined in /mydbr/defaults.php

Setup
Remote myDBR servers are defined in Admin tools -> Remote servers. The following fields needs to be defined:

• Servername The nickname for the remote server. This is used in reports to identify the remote server.

• URL Pointing to base of remote myDBR. Example: https://myotherserver.com/mydbr/

• Seed The URL seed for the remote server found in Environment settings -> Authentication / security -> URL
hash seed

• Username Username used to connect to remote server.

• Password Password used to connect to remote server.

Examples
We'll make a query to two different remote myDBR servers (my_remote_mydbr and my_other_mydbr). The first
remote call returns its data to an existing local table. For the second call we'll create a temporary table to hold
the remote call's data. You can have multiple remote calls before the actual report is executed.

DROP PROCEDURE IF EXISTS sp_DBR_remote_call


$$
CREATE PROCEDURE `sp_DBR_remote_call`(inDate date)
BEGIN

/*
mylocaltable is a normal table defined in database
*/
drop temporary table if exists remote_data_tmp;
create temporary table remote_data_tmp (
title varchar(255),
description text,

248
Commands

release_year year(4),
filmdate date
);

select 'dbr.remote.prepare', 'my_remote_mydbr', 'mylocaltable', 'sp_DBR_remote_first',


inDate;
select 'dbr.remote.prepare', 'my_other_mydbr', 'remote_data_tmp', 'sp_DBR_remote_other',
inDate;

select 'dbr.remote.call', 'sp_DBR_show_remote', inDate, 2;

END
$$

myDBR looks for the server's 'my_remote_mydbr' definition from the settings and calls a report
'sp_DBR_remote_first' in that server. while passing the inDate as a parameter. The result is stored into a
normal local table 'mylocaltable'. For the second remote call, the result will be put in to the recently created
'remote_data_tmp' temporary table. The remote call can contain only one result set and the format must match
the local table.

Note
Note that you can use temporary tables with MySQL. In MySQL temporary tables live remain after the
procedure has been completed (it lives until the connection is closed). In other databases, temporary
tables are removed once the procedure completes. In other databases one needs to use normal tables.

After the remote calls have been made, myDBR calls the local report (sp_DBR_show_remote) which shows the
data and drops the temporary table if created.

DROP PROCEDURE IF EXISTS `sp_DBR_show_remote`


$$
CREATE PROCEDURE `sp_DBR_show_remote`(inDate date, inNum int)
BEGIN

select * from mylocaltable;


select * from remote_data_tmp;
drop temporary table if exists remote_data_tmp;

END
$$

myDBR authenticates through http's basic access authentication, so make sure you use https calls or limit what
can be done with the username.

Troubleshooting
The most common error messages received when doing remote calls are the following:

No access privileges The user does not have access privileges to the report or the report specified
with dbr.remote.prepare does not exists

Report security hash does The security hash in the remote server definition does not match the one in
not match. Report execution remote server's environmental settings URL hash seed value
aborted.

Invalid login. Check the The username/password defined in the remote server definition is not correct
username and password for the
remote server.

249
Chapter 7. Extensions
myDBR allows you to create new extensions and modify existing extensions using the extension API. The API is
very simple and it allows you to write new commands for the myDBR language and implement new functionality.

Overview
A myDBR report can contain multiple result sets (single query result rows). Each of these result sets (the
raw data) is passed to result set handlers. myDBR comes with built-in result set handlers (table, cross
tabulation, charts, Graphviz elements, etc.). myDBR extensions consist of myDBR language commands and
associated result set handlers you can define yourself. For example, the Google Maps extension defines the
dbr.googlemaps-command and implements the Google Maps mashup functionality.

myDBR extensions consist of one or more myDBR commands (dbr.*) associated with the actual implementation
of the extension. Commands can have a variable number of parameters. As an example, the Google Maps
extension has one command (dbr.googlemaps) with parameters.

Extensions are written in PHP and reside in the extensions-directory. Each extension has its own subdirectory
under extensions-directory. The name of the directory is the same as the extension name. The PHP-file the
extensions.php contains the declarations for each extension. This file is read during report processing and
all active extensions introduced in the file are taken into use.

A special case of a myDBR extensions is a pass through extension, whose purpose is to take raw myDBR
query data, process it and pass the result back to myDBR result handlers. The result set from the pass through
extension can be completely different from the original data.

Processing the result set

The result sets from myDBR can be processed in a single pass or by row by row (a pass through extension
handles data in a single pass). The method you should choose depends on the functionality required and
number of data rows to be processed. If the number or data rows is small, it might be easier to use the single
pass approach. Choose the row by row method if the number of data rows is large thus lowering the memory
requirement for the server (for the cached data).

Single pass processing

In single pass processing myDBR parses the result into an array and then passes the data to the extension
(see 'single_pass_extension_function' below) in one call. In addition to the data array itself, additional
information of the result set (column datatypes, column lengths, result set id) is passed on to the extension
function.

Row by row processing

In row by row processing myDBR fist calls a function (see 'row_by_row_initialization' below) with the
information of the result set:

• $id ID of the result set (integer) to differentiate the result sets from each other

• $options extension commands with parameters used in the report in an array

array( 'command1' => array ( 'cmd1param1' => value, 'cmd2param2' => value2, ... ),
'command2' => array ( 'cmd2param1' => value, 'cmd2param2' => value2, ... ),
...
)

250
Extensions

array(
'name' => array( 0, 'col1name', 1, 'col2name', ... ),
'length' => array( 0, col1Length, 1, col2Length, ... ),
'datatype' => array( 0, 'col1datatype', 1, 'col2datatype', ... )
)

The datatypes are: char, int, float, bit, date or datetime

After each retrieved data row, myDBR then calls a function (see 'row_by_row_data_row' below). Data
elements in a data row are in a simple array.

To finish up, a final function call (see 'row_by_row_finish' below) is done after all the data rows have been
processed. The function has no parameters.

JavaScript
If your extension needs to include a JavaScript-file in the <HEAD>-section of the report, put the path to the
JavaScript-file into the 'javascript'-element.

extensions.php
The extensions.php-file declares the $dbr_extensions-array which contains the declarations for each
extensions in following format:

$dbr_extensions = array (
'MY_EXTENSION_NAME' => array(
'enabled' => true,
'php' => 'MY_EXTENSION_FILE.php',
'row_by_row_initialization' => 'ROW_BY_ROW_INIT_FUNCTION',
'row_by_row_data_row' => 'ROW_BY_ROW_DATA_ROW_FUNCTION',
'row_by_row_finish' => 'ROW_BY_ROW_FINISH_FUNCTION',
'single_pass_call' => 'SINGLE_PASS_CALL_FUNCTION',
'javascript' => array('MY_JAVASCRIPT.js'),
'passthrough' => false,
'cmds' => array(
array (
'cmd' => 'dbr.MY_COMMAND',
'MY_PARAMETER' => 1,
),
),
),
)

$dbr_extensions-array elements are the extensions declared. The key of each element
(MY_EXTENSION_NAME) is the subdirectory where the extension implementation resides.

For each extension following array key elements are defined:

• enabled Determines if the extension is active. If the extension is disabled, myDBR will not recognize the
commands and will not include the extension's javascript in the <HEAD> section

• autoload myDBR loads the extension's resources (JavaScript / CSS) automatically to all reports if the flag
is enabled. If not, the extension needs to be marked part of report in report info.

• javascript If the extensions requires a JavaScript file to be included in the <HEAD>-section, put the path to
your JavaScript(s) in this array. If none is required, leave the array empty.

• css If the extensions requires separate CSS file to be included in the <HEAD>-section, put the path to your
CSS(s) in this array. If none is required, leave the array empty.

251
Extensions

• php Name of the extension implementation file. If the extension is enabled, myDBR will include this
file when processing the report. Put only the filename here. The include is done from the extensions/
MY_EXTENSION_NAME-directory.

• row_by_row_initialization In row-by-row handling, this function is called before any data row is sent to the
extension.

• row_by_row_data_row This function is called for each data row when using the row-by-row handling. The
function gets an array of data values as a parameter.

• row_by_row_finish When all the rows have been processed in row-by-row handling, this function will be
called without parameters.

• single_pass_call When the result set has been processed by myDBR, it will call a function define here

• cmds This will declare the commands associated for the extension. The first command is treated as
the extension command. Subsequent commands can be used as options. For each command there is an
array element which contains the actual command ('cmd') and the named parameters. The parameters
('MY_PARAMETER) can be set as obligatory (1) or optional (0).

• mydbrextension If enabled, the extension is part of myDBR supplied extensions and can be found in
mydbr/extensions/extensions.php. User defined extensions should be declared in mydbr/user/extensions/
extensions.php

• passthrough The extension passes the processed data back to myDBR

Extension example
As an example, here is the Google Maps-extension definition:

'googlemaps' => array(


'enabled' => true,
'php' => 'googlemaps.php',
'row_by_row_initialization' => '',
'row_by_row_data_row' => '',
'row_by_row_finish' => '',
'single_pass_call' => 'Ext_GoogleMaps',
'javascript' => array('http://maps.google.com/maps?file=api&v=2&key='.
'ABQEBBCEees6cEI61aec2XA1XaA-iBK1zZo_VBU9_vcD2CFGhFOW5bxWknAOxF_EPvDl-
sEBB381ecgyOS6CaD'), // YOUR_GOOGLE_MAPS_API_KEY
'cmds' => array(
array (
'cmd' => 'dbr.googlemaps',
'mode' => 1, // 'coordinates' | 'address' (options for placing the marker)
'title' => 0, // Maps title
'width' => 0, // Width
'height' => 0, // Height
'x' => 0, // X latitude
'y' => 0, // Y longitude
'zoom' => 0, // Map zoom level
),
),
),

'googlemaps' is the name of the extension and therefore the PHP-file googlemaps.php, residing in the /
extensions/googlemaps-directory, will contain the function GoogleMaps($id, $options, $dataIn). The extension
is enabled, so the defined JavaScript is included to the report's <HEAD>-section.

'googlemaps' will introduce a command 'dbr.googlemaps' with one obligatory parameter (mode) and six optional
ones (title, width, height, x, y and zoom). When the GoogleMaps-function is called, it's 2nd parameter ($options)
will include the keys ['dbr.googlemaps']['parameter'] and values of these parameters.

252
Extensions

Note
You need to enable the Google Maps extension before you can use it. See more information about this
under the Google Maps extension.

Dummy extension example


Included is also (disabled by default) a dummy extension which just prints out the parsed data. You can use
this as a basis for your own extensions.

A passthrough extension
A passthrough extension is an extension which takes a result set in, processes it and passses back a result
set to myDBR. This allows using extensions data in myDBR report elements. A passthrough extension works
always as a single_pass_call.

A passthrough extension returns two arrays (data and columns) back to myDBR using Extension::result_set()
method. The data-array contains the data and the columns-array defines the column names and datatypes.

function Ext_Passthrough($id, $options, $dataIn, $colInfo )


{
/*
Do your stuff with the $dataIn which contains the data from the database.
*/

// This is the data we'll send back to myDBR


$data = array(
array('ABC', 'Q1', 10, '2016-10-22'),
array('ABC', 'Q2', 20, '2016-10-23'),
array('Third', 'Q1', 40, '2016-10-24')
);

// Define the columns: name & datatype


// Datatype needs to be one of following generic datatypes: char, float, int,
datetime, date, time
$columns = array(
array('name' => 'Sector', 'datatype' => 'char'),
array('name' => 'Quarter', 'datatype' => 'char'),
array('name' => 'Value[v]', 'datatype' => 'int'),
array('name' => 'Date[d]', 'datatype' => 'date')
);

// Pass it back to myDBR


Extension::result_set($data, $columns);
}

Google Maps extension


With the Google Maps extension, you can create Google Maps mashups easily. You can generate a report
object with a Google Map with markers placed in the map. The marker's speech bubble can contain your own
data. Placement of the pins can be done by using location data (latitude & longitude) or simply pass the address
on as a location.

Maps attributes: size, center and zoom value can be controlled with parameters. If no map attributes are given,
the default size of the map is used. The map is centered using markers and automatic zooming is done to fit
the markers into the map.

Commands
dbr.googlemaps - Display Google Maps mashup

253
Extensions

dbr.googlemaps.heatmap - Use Google Maps Heatmap layer


dbr.googlemaps.link_in_title - Whether to show single linked report in title or in the marker
dbr.googlemaps.polyline - Draw a polyline between the points
dbr.googlemaps.route - Draw route between the points
dbr.googlemaps.kml - Include KML-file into the maps
dbr.googlemaps.geojson - Include GeoJSON-file into the maps

Syntax

select 'dbr.googlemaps', 'coordinates' | 'address' {,title, width, height, lat, lng, zoom,
map_type}
select 'dbr.googlemaps.heatmap', 1[, 'HeatmapLayerOptions']
select 'dbr.googlemaps.link_in_title', true
select 'dbr.googlemaps.polyline', color, width
select 'dbr.googlemaps.route', 'driving' | 'walking' | 'bicycling' | 'transit'
select 'dbr.googlemaps.kml', url_to_kml_file
select 'dbr.googlemaps.geojson', url_to_geojson_file
Using address bubble:

select address, bubble_html {, marker {, shadow} }

Using latitude/longitude bubble:

select latitude, longitude, bubble_html {, marker {, shadow{, marker_label } } }

Using latitude/longitude-based heatmap (faster):

select latitude, longitude [, PointWeight] }

Using address-based heatmap (slower):

select address [, PointWeight] }

Where:

lat, lng latitude and longitude of the map center, use 0 to autocenter

map_type 'roadmap', 'satellite', 'terrain' or 'hybrid'

marker / shadow The optional 'marker' and 'shadow' are a URL to pictures to be shown on the map.
myDBR comes preinstalled with some of the common markers, but you can also
use your own pictures as markers. If you are using your own pictures the format is
'URL::x::y[::center]' where the x and y represent the size of the picture in pixels and
optional center parameter centers the marker.

HeatmapLayerOptions Optional Google Maps HeatmapLayerOptions as JavaScript object literals like


"dissipating:false,radius:2"

PointWeight The PointWeight object allows you to additionally specify a weight for that data
point. Applying a weight to a data point will cause the PointWeight to be rendered
with greater intensity.

Google Maps API key


myDBR Google Maps extension uses Google Maps API V3 and when addresses are used it uses server side
geocoding. If you have a Google Maps API key, you can use it in user/defaults.php by adding following line into it:

$mydbr_defaults['google_maps_api_key']='YOUR_API_KEY';

254
Extensions

Maps API for Business

The Maps API for Business agreement with Google gives you a better geocoding service with myDBR. To define
your Maps API for Business ID's add following line into user/defaults.php:

$mydbr_defaults['chart']['google_maps_business'] = array('client_id' => 'clientID',


'private_key' => 'vNIXE0xscrmjlyV-12Nj_BvUPaw=');

Where client_id is your client ID and private_key is your Private Key from your Maps API for Business
account.

Usage

/* Mashup based on address */


select 'dbr.googlemaps', 'address';

select address, bubble_html


from mydb.data;

/* Mashup based on coordinates */


select 'dbr.googlemaps', 'coordinates';

select latitude, longitude, bubble_html


from mydb.data;

Explanation

The command allows you to generate a Google Maps mahsup (map, markers on the map and the bubble). The
command has two variations of input, one with coordinated (latitude and longitude) and one with the address
based placing the marker.

Example - 'dbr.googlemaps' coordinates

Report place markers on map based on their latitude and longitude.

/* We'll zoom the map to Paris */


select 'dbr.googlemaps', 'coordinates', 'French sightseeing', 400, 400;

select 48.858863, 2.294362, 'la Tour Eiffel'


union
select 48.861397, 2.335432, 'Musee du Louvre';

255
Extensions

Example - 'dbr.googlemaps' address

Report place markers on map based on their address. Using address is quite flexible in Google Maps so we
can just place the names we're looking for. This will produce the same result as the example above. The first
column is used as the search criteria and the second one is used in the bubbles.

/* Center to US */
select 'dbr.googlemaps', 'address', 'Capitals of US States', 1200, 800;

select concat(state, ',', capital), capital


from mydb.us_states;

256
Extensions

Using preinstalled markers

myDBR comes with a set of preinstalled markers.

Here is the list of preinstalled markers and the URL to be used. With preinstalled markers myDBR automatically
knows the size of the maker and applies the appropriate shadow to it.

Plain URL Dot URL Pushpin URL


blue blue-dot blue-pushpin

green green-dot grn-pushpin

pink pink-dot pink-pushpin

purple purple-dot purple-pushpin

red red-dot red-pushpin

yellow yellow-dot ylw-pushpin

orange orange-dot

257
Extensions

Example usage of preinstalled markers

select 'dbr.googlemaps', 'address', 'French sightseeing', 400, 400;

select 'la Tour Eiffel', 'la Tour Eiffel', 'green'


union
select 'Musee du Louvre', 'Musee du Louvre', 'red-pushpin';

Using own markers

You can also use your own markers (any picture) with myDBR. To do this you need to provide the URL and the
size of the picture (using '::' notation at the end of URL).

Example usage of own markers

select 'dbr.googlemaps', 'address', 'French sightseeing', 400, 400;

select 'la Tour Eiffel', 'la Tour Eiffel', 'http://maps.google.com/mapfiles/ms/micons/


cabs.png::32::32'
union
select 'Musee du Louvre', 'Musee du Louvre', '/myimages/monalisa.jpg::58::51';

258
Extensions

Using Heatmaps

Heatmap support uses Google Maps Heatmap Layer.

Showing two heatmaps, one without options one with options

select 'dbr.googlemaps', 'coordinates';


select 'dbr.googlemaps.heatmap', 1;

select latitude, longitude


from mydata;

select 'dbr.googlemaps', 'coordinates';


select 'dbr.googlemaps.heatmap', 1, 'dissipating:false';

select latitude, longitude, weight


from mydata;

259
Extensions

Using custom SVG marker

You can use custom SVG markers in Google Maps by adding an SVG chart as a marker parameter.

SVG marker

Define the SVG image you wish to use as a marker:

<?xml version="1.0" encoding="UTF-8" standalone="no"?>


<svg xmlns="http://www.w3.org/2000/svg" width="100" height="100">
<circle cx="50" cy="50" r="49" fill="red" fill-opacity="0.2" stroke="gray" stroke-
width="1"/>
</svg>

select 'dbr.parameters.show';
select 'dbr.googlemaps', 'coordinates', 'Biggest cities in US', 700, 500;

select latitude, longitude, name, f_map_city_size(''user/images/circle.svg', population),


'','', population
from us_cities
order by population desc;

where the f_map_city_size-function returns the size (in pixels) of the SVG image relative to population. For
example: "user/images/circle.svg::160::160::center".

260
Extensions

Routes

The route option allows for route planning

select 'dbr.googlemaps', 'address', '', 500, 600;


select 'dbr.googlemaps.route', 'walking';

select 'Parc Monceau, Paris'


union
select 'Arc de Triomphe'
union
select 'Eiffel tower';

261
Extensions

Include a KML-file and GeoJSON file and extend map functionality

You can also include a KML and GeoJSON files to the map and access the Google Maps API in your report
to further extend the map functionality

The Google_map.get_map_object-function can be used to get the Google Maps object. The function takes a
resultclass as a parameter.

Show Chicago Transit Map

select 'dbr.resultclass', 'sample_map';


select 'dbr.googlemaps', 'coordinates', '', 700, 850, 0, 0, 9;
select 'dbr.googlemaps.kml', 'http://googlemaps.github.io/js-v2-samples/ggeoxml/cta.kml';
select 'dbr.googlemaps.geojson', 'user/chicago.geojson';

select 'Chicago';

262
Extensions

select 'dbr.javascript',
"Google_map.get_map_object('sample_map').data.setStyle({fillColor:
'#94F2AC',strokeColor:'#888' ,strokeWeight: 1});";

263
Extensions

Geocode caching
myDBR will cache the geocode results (address to latitude/longitude conversion) into mydbr_geocode-table.
One can disable the feature with $mydbr_defaults['geocode']['cache']-option.

OpenStreetMap extension
With the OpenStreetMap extension, you can create OpenStreetMap mashups easily. You can generate a report
object with a OpenStreetMap with markers placed in the map. The marker's speech bubble can contain your
own data. Placement of the pins can be done by using location data (latitude & longitude) or simply pass the
address on as a location.

OpenStreetMap can use different tile servers on top of the data. You can use them as alternative for
OpenStreetMap's own tiles.

myDBR uses Leaflet JavaScript library as API to OpenStreetMap. For heatmaps, myDBR uses Leaflet plugin
Leaflet heat.

Map bubbles can be customized with Leaflet.ExtraMarkers

Commands
dbr.openstreetmap - Show OpenStreetMap
dbr.openstreetmap.heatmap - Use OpenStreetMap layer
dbr.openstreetmap.tiles - Use alternative tiles on top of OpenStreetMap
dbr.openstreetmap.geojson - Include GeoJSON-file into the maps

Syntax

select 'dbr.openstreetmap', 'coordinates' | 'address' {,title, width, height, zoom}


select 'dbr.openstreetmap.heatmap', 1[, leafletheat_options]
select 'dbr.openstreetmap.tiles', tile_server_url [, tiles_options]
select 'dbr.openstreetmap.geojson', url_to_geojson_file
Using address bubble:

select address, bubble_html

Using latitude/longitude bubble:

select latitude, longitude, [bubble_html [, '{bubble_options}']]

Using latitude/longitude-based heatmap:

select latitude, longitude [, PointWeight] }

Using address-based heatmap:

select address [, PointWeight]

Where:

Leafletheat_options Optional options for Leaflet heat like "{radius: 25}"

Property Description
minOpacity the minimum opacity the heat will start
at
maxZoom zoom level where the points reach
maximum intensity (as intensity scales

264
Extensions

with zoom), equals maxZoom of the


map by default
max maximum point intensity, 1.0 by default
radius radius of each "point" of the heatmap,
25 by default
blur amount of blur, 15 by default
gradient color gradient config, e.g. {0.4: 'blue',
0.65: 'lime', 1: 'red'}

tiles_options Optional options required by the used tiles server

PointWeight The PointWeight object allows you to additionally specify a weight for that data
point. Applying a weight to a data point will cause the PointWeight to be rendered
with greater intensity. The default weight is 1

bubble_options Bubble options are the options defined in Leaflet.ExtraMarkers

Property Description Default Value Possible values


extraClasses Additional classes '' fa-rotate90
in the created <i> myclass; space
tag delimited classes
to add
icon Name of the icon '' fa-coffee (see
with prefix icon library's
documentation)
iconColor Color of the icon 'white' 'white',
'black' or css
code (hex, rgba
etc)
innerHTML Custom HTML '' <svg>, images,
code or other HTML; a
truthy assignment
will override the
default html icon
creation behavior
markerColor Color of the marker 'blue' 'blue', 'red',
(css class) 'orange-dark',
'orange',
'yellow',
'blue-dark',
'cyan',
'purple',
'violet',
'pink', 'green-
dark', 'green',
'green-light',
'black', or
'white'
number Instead of an icon, '' '1' or 'A', must
define a plain text set icon: 'fa-
number'
prefix The icon library's 'glyphicon' 'fa' (see
base class icon library's
documentation)

265
Extensions

shape Shape of the 'circle' 'circle',


marker (css class) 'square',
'star', or
'penta'

Usage

Sample map with address

/* Mashup based on address */


select 'dbr.openstreetmap', 'address';

select 'Paris', 'Paris, France';

Sample map with latitude and longitude

/* Map based on address */


select 'dbr.openstreetmap', 'address';

select 'Paris', 'Paris, France';

Sample map with latitude and longitude

/* Map based on coordinates */

266
Extensions

select 'dbr.openstreetmap', 'coordinates';

select latitude, longitude, bubble_html


from mydb.cities;

Using Heatmaps

select 'dbr.openstreetmap', 'coordinates','', 900, 500;


select 'dbr.openstreetmap.heatmap', 1;

select lat, lng, weight


from heatmap;

267
Extensions

Customizing markers
Adding FontAwsome icons (included in myDBR) into the markers

select 'dbr.openstreetmap', 'coordinates', '', 400, 220;

select 33.005, -117.270, '', "{icon: 'fa-spinner',shape: 'circle',markerColor:


'red',prefix: 'fa',extraClasses: 'fa-spin'}"
union
select 33.005, -117.265, '', "{icon: 'fa-coffee',shape: 'square',markerColor: 'orange-
dark',prefix: 'fa',iconColor: 'black'}"
union
select 33.005, -117.260, '', "{icon: 'fa-cog',shape: 'star',prefix: 'fa',markerColor:
'blue',iconColor: 'white'}"
union
select 33.005, -117.255, '', "{icon: 'fa-spinner',shape: 'penta',markerColor: 'green-
dark',iconColor: 'white', prefix: 'fa'}"
;

268
Extensions

Using different tile layers


With OpenSteetMap you can use different tile layers in the map. In the example we'll use MapBox's tile layer.
To use the tile layers, you pass the URL to the tile layer with the dbr.openstreetmap.tiles-command
with optional options. In the example we'll choose run-bike-hike-layer by passing the "id:'mapbox.run-bike-hike'"
option to MapBox.

select 'dbr.openstreetmap', 'address', 'Marinwood run-bike-hike tile', 500, 500, 13;


select 'dbr.openstreetmap.tiles', 'https://api.tiles.mapbox.com/v4/{id}/{z}/{x}/{y}.png?
access_token=pk.eyJ1IjoibWFwYm94IiwiYSI6ImNpejY4NXVycTA2emYycXBndHRqcmZ3N3gifQ.rJcFIG214AriISLbB6B
"id:'mapbox.run-bike-hike'";

select 'Marinwood', 'Marinwood';

Embedding GeoJSON files


You can also extend the map by including GeoJSON files to the map

select 'dbr.openstreetmap', 'address', 'Chicago', 700, 850;


select 'dbr.openstreetmap.geojson', 'user/chicago.geojson';

269
Extensions

select 'Chicago', 'chicago';

Geocode caching

myDBR will cache the geocode results (address to latitude/longitude conversion) into mydbr_geocode-table.
One can disable the feature with $mydbr_defaults['geocode']['cache']-option.

270
Extensions

Mail extension
With mail extension, you can send mail directly from the report. SMTP mail is supported as well as support for
authentication. myDBR utilizes PHPMailer.

Configuration
Configuration is done via Environmental settings. Old mail configuration in user/extension_init.php is
deprecated.

Commands
dbr.mail - Send mail
dbr.mail.sender - Provide sender address in the report instead of using the one from the settings (user/
extension_init.php)
dbr.mail.recipient - Add multiple recipients to the mail to be sent
dbr.record - Record report output for mail delivery or to be used with a template
dbr.mail.attach - Add attachment to mail
dbr.mail.notify_successful_mail - Disable the "Mail sent" message
dbr.mail.smtp.user - Use alternate SMTP user/password
dbr.mail.smtp.server - Use alternate SMTP server
dbr.mail.smtp.authentication.type - Select SMTP authentication (default LOGIN)
dbr.mail.smtp.nlmt.realm - Realm for NTLM authentication type
dbr.mail.smtp.nlmt.workstation - Workstation for NTLM authentication type
dbr.mail.encoding - Set the mail encoding ("8bit", "7bit", "binary", "base64" and "quoted-printable")
dbr.mail.debug - Set debug on to get verbose error messages (1=debug on,0=debug off)
dbr.mail.log.proc - Define a procedure which will log the mail actions.
dbr.mail.nobr.html - Do no convert linefeeds to line breaks in HTML mail

Syntax

select 'dbr.mail', [optional HTML flag: 1 for HTML mail]


select 'dbr.mail.sender', sender_email, [, sender_name, [replyto_email, [replyto_name ]]]
select 'dbr.mail.recipient', recipient_email, [, recipient_name, 'cc' | 'bcc']
select 'dbr.record', 'begin' [, 'template_variable' ] | 'end'
select 'dbr.mail.attach', 'filename.ext', URL
select 'dbr.mail.notify_successful_mail', 0
select 'dbr.mail.smtp.user', 'user', 'password'
select 'dbr.mail.smtp.server', 'host', 'port', {'tls'|'ssl'}
select 'dbr.mail.smtp.authentication.type', 'LOGIN' | 'PLAIN' | 'NTLM' | 'CRAM-MD5'
select 'dbr.mail.smtp.nlmt.realm', 'realm'
select 'dbr.mail.smtp.nlmt.workstation', 'workstation'
select 'dbr.mail.encoding', 'base64'
select 'dbr.mail.debug', 1
select 'dbr.mail.log.proc', 'sp_mail_log';
select 'dbr.mail.nobr.html', 1;

In dbr.mail.sender, if no replyto_email is given, myDBR uses sender_email. Similarly if


replyto_name is not given sender_name is used.

Usage
Plain text mail

select 'dbr.mail';

select 'John.Doe@example.com', 'John', 'This is a subject', 'Body of the mail';

271
Extensions

HTML mail with mail debug log

/* Send HTML mail */


select 'dbr.mail', 1;
select 'dbr.mail.log.proc', 'sp_mail_log';

select email, name, subject, html_body


from mydb.mail_recipients;

Where the sp_mail_log procedure has format:

create procedure sp_mail_log (


in_msg varchar(255),
in_error text,
in_to_address varchar(255),
in_errornous_attachment_names varchar(255)
)
begin

insert into mail_log(sent_at, message, error, to_address, errornous_attachment_names)


values ( now(), in_msg, in_error, in_to_address , in_errornous_attachment_names );

end

Same mail to multiple recipients

select 'dbr.mail';
select 'dbr.mail.recipient', 'john@company.com', 'John Doe', 'CC';
select 'dbr.mail.recipient', 'Jane@company.com', 'Jane Doe', 'BCC';
select 'dbr.mail.recipient', 'father@company.com', 'Father Doe';

/* We can skip the recipient as we already have them */


select '', '', 'Notification',
concat('Your report can be found in myDBR', char(10),
'-- ', char(10),
'Mary');

Mail with different sender & Reply-To

select 'dbr.mail';
select 'dbr.mail.sender', 'mary@company.com', 'Mary Cotton';

select 'john@company.com', 'John Doe', 'Notification',


concat('Your report can be found in myDBR', char(10),
'-- ', char(10),
'Mary');

Sending report output as mail

In order to send full report elements to mail, you can use the dbr.record command to gather data to be mailed.
The command includes 'begin' and 'end' commands which will mark the section to be included in the mail. The
dbr.record-command is available in the Premium-version.

The command will:

272
Extensions

• Include the report objects while preserving the formatting

• Include all table elements (basic, cross tabulation, pageview etc)

• Include images (ChartDirector, Graphviz) as attachments

The command will not:

• Include elements which require client side processing (GoogleMaps, Flash-charts)

/* We'll start recording, everything between 'begin' and 'end' will be included into
report */
select 'dbr.record', 'begin';

/* Include full reports */


call sp_DBR_MyReport();

/* Include additional report elements */


select data1, data2
from mydb.mydata;

select 'dbr.record', 'end';

/* We'll use HTML mail to preserve the formatting */


select 'dbr.mail', 1;

/* And finally send the mail to all recipients */


select email, name, 'This is the report'
from mydb.mail_recipients;

Using attachments

You are free to add attachments to mails. An attachment can be any file accessible from the server including
a PDF/Excel export from myDBR itself.

select 'dbr.mail';
select 'dbr.mail.sender', 'mary@company.com', 'Mary Cotton';
select 'dbr.mail.attach', 'report.pdf', 'http://myserver.com/mydbr/report.php?
r=184&h=ee5f3bfee6e1384ccf52e151bcc2081aa367adeb&export=pdf';

select 'john@company.com', 'John Doe', 'Notification',


concat('Here is the latest report', char(10),
'-- ', char(10),
'Mary');

Push Notification extension


With Push Notification extension, you can send Push Notifications to your iOS, Android or Desktop devices.
With this you can trigger alerts / notifications for important things happening in your system. You can do this
both in interactive reports and in Scheduled reports.

Following Push Notification services are supported (you need to download the respective app to your device
from the app store):

• Pushbullet. iOS, Android and Desktop

• Pushover. iOS, Android

273
Extensions

• Prowl. iOS

Configuration
Configuration is done via user/extension_init.php. The $mydbr_push array contains the 'sender' key which marks
the default service you are going to use (you can override it in a report using dbr.push.options). For Pushover
and Pushbullet, you will need an app/access token which identifies you as a sender.

$mydbr_push = array(
'sender' => "pushover", // Default sender: pushover, pushbullet, prowl
'pushover_app_api_token' => "APP_TOKEN",
'pushbullet_access_token' => "ACCESS_TOKEN"
);

Commands
dbr.push - Send a push message
dbr.push.sender - Choose another sender than the one defined in $mydbr_push init
dbr.push.option - Set a service specific option
dbr.push.notify_successful_push - Disable the "Push message sent" message
dbr.push.log.proc - Log the push message activity to database
dbr.push.debug - Show status for each message sent

Syntax

select 'dbr.push';
select 'dbr.push.sender', 'pushover' | 'pushbullet' | 'prowl'
select 'dbr.push.option', 'option', 'value'
select 'dbr.push.notify_successful_push', 0
select 'dbr.push.log.proc', 'sp_log_stored_procedure'
select 'dbr.push.debug', 1

Options for Pushbullet:

access_token If not provided in $mydbr_push

target Target the message to specific device. Possible values 'device_iden', 'email', 'channel_tag',
'client_iden'. See Pushbullet documentation for details.

Options for Pushover:

token If not provided in $mydbr_push

device Your user's device name to send the message directly to that device, rather than all of the user's
devices

url A supplementary URL to show with your message

url_title A title for the URL

priority send as -2 to generate no notification/alert, -1 to always send as a quiet notification, 1 to display


as high-priority and bypass the user's quiet hours, or 2 to also require confirmation from the user

timestamp A Unix timestamp of your message's date and time to display to the user, rather than the time
your message is received by our API

sound The name of one of the sounds supported by device clients to override the user's default sound
choice

Options for Prowl: providerkey', 'priority', 'application

274
Extensions

providerkey Your provider API key. Only necessary if you have been whitelisted

priority -2: Very Low, -1: Moderate, 0: Normal, 1 High, 2 Emergency

application The name of your application or the application generating the event

Usage
Send a notification when sender is defined

select 'dbr.push';

select 'John.Doe@gmail.com', 'Sales exceed $1M', 'Check the latest sales figures https://
company.com/mydbr/report';

Define a sender and options

/* Send HTML mail */


select 'dbr.push';
select 'dbr.push.option', 'device', 'phone';
select 'dbr.push.option', 'sound', 'magic';
select 'dbr.push.log.proc', 'sp_mail_log';
select 'dbr.push.notify_successful_push', 0;
select 'dbr.push.sender', 'popover';

select 'us2e8xm87wiiba4s6vb3ik68pmqpfr', 'Title', 'Message body';

275
Extensions

eChart extension
eChart extension is provided as a skeleton extension to enable the use of extra charts in ChartDirector. It
implements Bubble and Radar chart as an example. Full source code is included. The eChart extension is
placed in the user-directory and therefore any modifications made to it will be retained in myDBR update.

Commands
dbr.echart - Create an extended chart
dbr.echart.color - Select colors for the chart
dbr.echart.name - Select category names
dbr.echart.bubble_scale - Scale bubble chart axis

Syntax

select 'dbr.echart', 'radar' | 'bubble'


select 'dbr.echart.color', 'ARGB color1', 'ARGB color2'...
select 'dbr.echart.color', 'Category 1', 'Category 2'...
select 'dbr.echart.bubble_scale',1

Usage
Create a radar chart

select 'dbr.echart', 'radar', 'Example radar';


select 'dbr.echart.color', '0x80ff3333', '0x803333ff';
select 'dbr.echart.name', 'Model Saturn', 'Model Jupiter';

select Speed, Reliability, Comfort, Safety, Efficiency


from radar_data;

276
Extensions

Create a bubble chart


Since the axis will be automatically scaled and can contain different datatypes, the bubble size (z) is by default in
pixels. If you want to use absolute sizes for bubble size, use the select 'dbr.echart.bubble_scale',1
command to scale the axis. After this the bubble size is relative to the axis.

select 'dbr.echart', 'bubble', 'Bubble chart';


select 'dbr.echart.color', '0x80ff3333', '0x803333ff','0x80FF33ff';

select select x, y, z, category


from bubble_data;

d3 extension
d3 extension is a framework for D3 JavaScript library.

Commands
dbr.d3 - Create a d3 object
dbr.d3.sankey_format - Format the Sankey tooltips
dbr.d3.zoom - Zoom the chord diagram when data has long texts

Syntax

select 'dbr.d3', 'chart_type'


select 'dbr.d3.sankey_format', 'd3_numeric_format', 'number_suffix'...

277
Extensions

select 'dbr.d3.zoom', pixels

Usage
A Sankey diagram is a flow diagram, in which the width of the arrows is shown proportionally to the flow quantity.

Use the one of the followin data selection. In first, the nodes are identified by name and in the second, by id.

select source, target, value


from mydb.Data;

select source_id, source, target_id, target, value


from mydb.Data;

A Sankey diagram

select 'dbr.d3', 'sankey', 'UK energy production and consumption in 2050',960, 500;
select 'dbr.d3.sankey_format', ',.0f', ' Twh';

select source, target, value


from demo_uk_energy;

A chord
A chord diagram shows inter-relationships between data in a matrix.

A cord data shows connected nodes with value

select `to`, `from`, value


from mydb.Data;

278
Extensions

Create a Chord diagram

select 'dbr.d3', 'chord', 'Debt diagram';

select creditor, debtor, value


from debts;

SMS extension
With SMS extension you can send SMS (text messages) to mobile phones. myDBR currently supports sending
SMS via Clickatell. Before you can send SMS you need to sign up for an account with Clickatell. See also that
the numbers you use comply with the format used with Clickatell.

Other SMS gateways can be used by extending the SMSSender class in extensions/sms/
sms_sender.php

Configuration
Make sure that you have created a HTTP API connection from Clickatell central. After that add your access
details for the Clickatell SMS gateway in user/extension_init.php.

Commands
dbr.sms - Send SMS

279
Extensions

dbr.sms.sender - Provide a sender ID for the outgoing message. Note: Sender ID's need to be requested
and approved from Clickatell before they can be used.

Syntax

select 'dbr.sms', {optional simulate flag: 1 for simulating sending}


select 'dbr.sms.sender', sender_id

When simulating the sending, the Clickatell URL is displayed and the actual sending is not done.

Usage
Sending standard SMS

select 'dbr.sms';

select phone_nr, message


from mydbr.sms_recipients;

Sending with specified sender ID

select 'dbr.sms';
select 'dbr.sms.sender', 'mydbr.com';

select '12345789', 'Hello from myDBR'


union
select '43123454', 'Another message from myDBR';

Organization chart extension


The Organization chart extension allows the creation of optimized organization charts. It uses HTML5 Canvas for
the charts. Organization nodes can be positioned left, right and under their ancestor node allowing the creation
of compact organization charts.

In most cases, databases contain the information about the organization hierarchy (parent-child), but not the
positioning of the node (left, right and under). What can be done, is that a linked report is attached to the node
so that the positioning can be selected when the chart is shown. See example below.

The extension will automatically calculate the size of the chart and the nodes. You can define various parameters
with the options.

Organization nodes can optionally contain targets (KPI metrics). This allows an organization chart to be used
for showing organization target setting. See example below.

Commands
dbr.org.chart - Display organization chart
dbr.org.chart.export - Show "Export as PNG" button in the chart
dbr.org.target - Add a target to the node

Syntax

select 'dbr.org.chart' {,options}


select 'dbr.org.chart.export', 1
select 'dbr.org.target', node_id, weight, 0, color, text
Data query:

280
Extensions

select id, parent_id, 'l' | 'r' | 'u' | 'a', text, url, fillcolor, linecolor

Where options is a JSON string. The options include:

lineColor Color of the connection lines. Default is "#3388DD"

lineWidth Connection line width. Default is 1

boxWidth Node width. If not defined it will be automatically calculated.

boxHeight Node height. If not defined it will be automatically calculated.

hSpace Horizontal space in between the boxes. Default is 20px

vSpace Vertical space in between the boxes. Default is 20px

boxLineColor Node edge line color. Default is "#B5D9EA"

boxFillColor Node fill color. Default is "#CFE8EF"

boxPadding Node padding. Default is 16px

textColor Node text color. Default is "#000000"

textFont Node text font. Default is 'arial'

textSize Node text size. Default is 12px

textPadding Pixels between lines. Default is 0

boxWidthMin Minimum node width when calculated automatically. Default is 0

boxHeightMin Minimum node height when calculated automatically. Default is 0

shadowOffsetX Node x-axis shadow offset. Default is 3px

shadowOffsetY Node y-axis shadow offset. Default is 3px

shadowColor Node shadow color. Default is "#A1A1A1"

radius Node corner radius. Default is 5px

autobalance Balance left and right nodes automatically. Default is 'auto'. Values can be 'l', 'r' and 'auto'

Target parameters are: node_id, weight, 0, color, text

node_id Node where the target is attached to

weight target width in node: weight / (sum of all target's weights in node)

target reserved, use 0

color Color to be used to show the target in the chart

text Tooltip to be shown when user hovers over the target

Usage

select 'dbr.org.chart';

281
Extensions

select id, parent_id, position, name


from mydb.organizationdata;

The topmost node has a parent_id value of null and the position is a string 'r', 'l', 'u' or 'a' (right, left, under, auto).

Defining the node positions


A node can be positioned left, right or under from it's parent node. You can define the explicit position (by using
left, right or under) or let myDBR automatically balance the chart by assigning node automatic ('a') position.

When automatic balancing is chosen, myDBR will put nodes without siblings to left and right (didived equally)
and the nodes with siblings to under. The left and right balancing can be adjusted with the 'autobalance' option
(value of 'l' will put all nodes without siblings to left and value of 'r' to the right).

With default automatic balancing left and right siblings are balanced. The chart becomes wider and shorter. The
"Business Support"-node is placed left as it does not have siblings whereas other nodes in the same level are
placed under. This will be suitable for organization charts where there are few siblings for a node.

select 'dbr.org.chart';

select o.id, o.parent_id, 'a', o.name


from mydb.organizationdata;

282
Extensions

When autobalance is det to 'l' (or 'r') left and right siblings are balanced into one side. The chart becomes taller
and more narrow. This will be suitable for organization charts where there are many siblings for a node.

select 'dbr.org.chart', '{autobalance:"l"}';

select o.id, o.parent_id, 'a', o.name


from mydb.organizationdata;

You can also mix static positions ('l', 'r', 'u' ) with automatic position. Let myDBR do the initial placement and
finetune with static positions.

Allow node positioning dynamically within the report


To create perfect organization charts, one can dynamically adjust positions by using linked reports. We'll create
a table called 'organization_node_positions' which will hold the node ID and the position information. A linked
report is attached to the nodes to handle the positioning of individual nodes.

select 'dbr.org.chart';

select 'dbr.report', 'sp_DBR_set_node_position', 'action_div[]', 'in_id=id', 'in_pos="l"',


'"Position left"';

283
Extensions

select 'dbr.report', 'sp_DBR_set_node_position', 'action_div[]', 'in_id=id', 'in_pos="r"',


'"Position right"';
select 'dbr.report', 'sp_DBR_set_node_position', 'action_div[]', 'in_id=id', 'in_pos="u"',
'"Position under"';

select o.id, o.parent_id, ifnull(p.position, 'u'), o.name


from mydb.organizationdata
left join organization_node_positions p on p.id=n.id;

Where 'action_div[]' is dymanically ([]) created embed_object for the output of sp_DBR_set_node_position. The
positions are set with one procedure with different parameters (l,r,u) and link name.

Where the linked report set's the node position and refreshes the chart:

CREATE PROCEDURE `sp_DBR_set_node_position`(


in_id int,
in_pos char(1)
)
begin

delete from organization_node_positions where id=in_id;

insert into organization_node_positions (id, pos)


values (in_id, in_pos);

select 'dbr.refresh';

end

Using options and formatting the nodes

select 'dbr.org.chart', '{boxWidth:140,boxheight:30,textPadding:6}';

select id, parent_id, position, concat('<b>',name,'</b>, char(10), person), '',color


from mydb.organizationdata;

This will create a chart with a node width of 140px and height of 30px. Between the lines in the node (organization
node name and responsible) there is 6px padding. The organization name is bolded with <b> and color is defined
node by node.

Full organization chart with positioning and targets

284
Extensions

select 'dbr.title', 'Target browser';

select 'dbr.report', 'sp_DBR_organization_set_node_position', 'action_div[]', 'in_id=id',


'in_pos="l"', '"Position left"';
select 'dbr.report', 'sp_DBR_organization_set_node_position', 'action_div[]', 'in_id=id',
'in_pos="r"', '"Position right"';
select 'dbr.report', 'sp_DBR_organization_set_node_position', 'action_div[]', 'in_id=id',
'in_pos="u"', '"Position under"';

select 'dbr.org.chart', '{boxWidth:180}';

select 'dbr.org.target', organization_node_id , weight, 0, color, txt


from mydb.organizationdata;

select
id,
parent_id,
fn_org_node_position( id, type_id ),
concat('<b>', name, '</b>', char(10), owner, char(10) ) /* Last linefeed makes room
for the targets */
from organization3
order by id;

Where 'sp_DBR_organization_set_node_position' allows node positioning.

CREATE PROCEDURE `sp_DBR_organization_set_node_position`(


in_id int,
in_pos char(1)
)
begin

delete from organization_node_positions where id=in_id;

insert into organization_node_positions (id, pos)


values (in_id, in_pos);

select 'dbr.refresh';

end

And the 'fn_org_node_position'-function determines the node position. It looks for the defined position from the
organization_node_positions-table, if not found, it uses the default.

CREATE FUNCTION `fn_org_node_position`( in_id int, in_type int ) RETURNS char(1)


begin

declare vPos char(1);

select pos into vPos


from organization_node_positions
where id=in_id;

if (vPos is not null) then


return vPos;
end if;

return 'u';

end

285
Extensions

This will create an organization chart where node positions can be changed by clicking into the node. Targets
are shown in color and hovering over the target shows the details.

Barcode extension
The Barcode-extension utilizes Johan Lindell's JsBarcode JavaScript library. The supported barcode types are

• CODE128 (auto and force mode)

• CODE39

• EAN-8

• EAN-5

• EAN-2

• UPC (A)

• ITF-14

• ITF

• MSI10

• MSI11

• MSI1010

• MSI1110

• Pharmacode

Commands

dbr.barcode - Show the barcode

Syntax

select 'dbr.barcode' barcode | JSBarcode_object[, tag]

286
Extensions

Where:

barcode Any of the supported barcodes

JSBarcode_object See JsBarcode

tag Decide the HTML tag where the barcode will be enclosed into (svg, canvas, img). The
default is img.

Usage

The parameter for the dbr.barcode-command can be either the barcode type, or one can define all the options
available in JSBarcode directly in the parameter. See JsBarcode-website for available options.

select 'dbr.keepwithnext';
select 'dbr.subtitle', 'CODE128';
select 'dbr.barcode', 'CODE128';

select '123456779';

select 'dbr.subtitle', 'CODE128C';


select 'dbr.barcode','{format: "CODE128C", width:1, height:35, fontSize:10}';
select '558101710000001220004829906000000559582243294671100131';

select 'dbr.keepwithnext', 'reset';

select 'dbr.keepwithnext';
select 'dbr.subtitle', 'EAN13';
select 'dbr.barcode','{format: "EAN13", lastChar: ">"}';
select '1234567890128';

select 'dbr.subtitle', 'UPC';


select 'dbr.barcode','UPC';
select '123456789999';

select 'dbr.keepwithnext', 'reset';

select 'dbr.keepwithnext';
select 'dbr.subtitle', 'ITF14';
select 'dbr.barcode','ITF14';
select '12345678901231';

select 'dbr.subtitle', 'MSI';


select 'dbr.barcode','MSI';
select '123456789';

select 'dbr.keepwithnext', 'reset';

select 'dbr.keepwithnext';
select 'dbr.subtitle', 'pharmacode';
select 'dbr.barcode','{format: "pharmacode", width:1, height:40, displayValue: true}',
'svg';

287
Extensions

select '1234';

select 'dbr.subtitle', 'codabar';


select 'dbr.barcode','codabar';
select '1234567890';

QR code extension
The QR code-extension utilizes Sangmin, Shim's QRCode.js JavaScript library.

Commands
dbr.qrcode - Show the QR code

288
Extensions

Syntax

select 'dbr.qrcode'

Usage

The data for the dbr.qrcode-command can be either the included text or the options available in QRCodejs
QRCode.js-website for available options.

select 'dbr.keepwithnext';
select 'dbr.subtitle', 'URL';
select 'dbr.qrcode';

select 'https://mydbr.com';

select 'dbr.subtitle', 'Email';


select 'dbr.qrcode';

select 'mailto:sales@mydbr.com';

select 'dbr.keepwithnext', 'reset';

select 'dbr.keepwithnext';
select 'dbr.subtitle', 'Telephone';
select 'dbr.qrcode';

select 'tel:+1-000-000-0000';

select 'dbr.subtitle', 'Geolocation with options';


select 'dbr.qrcode';
select '{
text: "geo:60.16997,24.93853",
width: 128,
height: 128,
colorDark : "#67a814",
colorLight : "#ffffff",
correctLevel : QRCode.CorrectLevel.H
}';

289
Extensions

290
Chapter 8. Supported datatypes
MySQL
The following data types are supported as user report parameters and in the report select columns.

Numeric
tinyint
smallint
int
mediumint
bigint
float
double
decimal
year

Date and time


timestamp
date
time
datetime

Character
char
varchar
tinyblob (*)
mediumblob (*)
longblob (*)
blob (*)
tinytext
mediumtext
longtext
text

Time datatype can be used as regular time or as duration.

When used as regular time, the column is formatted based on the format defined in the preferences. Regular
time has range of 00:00:00 - 23:59:59.

If you apply a style '%s' to a time column or use aggregate function sum or avg, the time column is then treated
as duration and the format is always H:M:S.

(*) For text data

291
Supported datatypes

Microsoft SQL Server, Sybase ASE, SQL Anywhere


Numeric
bit
tinyint
smallint
int
bigint
float
decimal
numeric
real
smallmoney
money

Date and time


smalldatetime
datetime
date (*)
time (*)
datetime2 (*) (**)
datetimeoffset (*)

Character
char
nchar
varchar
nvarchar
text
ntext
sysname

(*) For SQL Server 2008 and newer.

(**) Not supported in Sybase ASE / SQL Anywhere

Note that FreeTDS does report does not identify date datatypes datatypes correctly. Use ':type=date' notation
in column name to specify the correct datatype.

declare @d date
declare @dt datetime2
declare @time time
declare @datetimeoffset datetimeoffset

select @d = getdate(), @dt = getdate(), @time = getdate(), @datetimeoffset = getdate()

292
Supported datatypes

select @d as 'date:type=date',
@dt as 'datetime2:type=datetime',
@time as 'time:type=time',
@datetimeoffset as 'datetimeoffset:type=datetime'

293
Chapter 9. Security
We are working hard to ensure that myDBR is secure. myDBR is updated regularly and these updates in addition
to new features, may also contain improvements to security.

Security considerations
The things listed below ensure that your installation of myDBR is also secure.

• Change the default admin username / password

• Use HTTPS whenever possible

• Define a unique URL hash seed in Environment settings → Authentication / security

• Enforce password rules in Environment settings → Password settings when using myDBR authentication

• Keep your server up to date

• Limiting admin rights to PHP

Change the default admin username


When myDBR is installed, an admin user is created under name 'dba' with a default password. It is recommended
that you create another admin user with secure password and disable the original one. Note that this should be
done regardless of authentication method in use as local logins are always accessible.

Use HTTPS whenever possible


When the server is configured to only accept connections over secure HTTPS connection, it will protect all
information sent. This will include your authentication information, data and session information.

URL hash seed


All myDBR reports are accessible via an URL. In order to make sure that a URL is generated by a trusted source
(myDBR itself or admin wish access to data required for URL generation) the URL is checked against a hash
value which is added to the URL. The hash value is calculated from the URL parameters and with the URL hash
seed which is installation specific. To make sure your reports have a unique hash value, click the Randomize-
button in "URL hash seed" in Environment settings → Authentication / security

Enforce password rules


Enforcing password rules makes passwords harder to guess. See the Wikipedia article about password policy.

Keep your server up to date


Make sure your server is up-to-date. This includes all software components in your server: operating system,
server software (web server, PHP), myDBR itself.

Limiting admin rights to PHP


By default, myDBR extends it's functionality by offering PHP access to admins. This included capability to create
myDBR extensions, more customization for extending existing myDBR commands etc.

With PHP access admin can also access resources inside the server via PHP's filesystem services. If you offer
myDBR admin access to users that should not have access to server files, you can limit the PHP access by
adding following line to user/defaults.php

294
Security

$mydbr_defaults['admin_restrictions']['can_access_php'] = false;

The setting will prevent admin access to PHP files in 'Server side files'-functionality and prevents admins from
using PHP commands to extend existing commands.

295
Chapter 10. myDBR SQL Editor
Editor basics
The myDBR SQL Editor is a built-in editor for accessing reports and other database objects in the database.
You can create reports, query data, update data or run any sql command against the selected database.

When SQL Editor is started´, the following options are shown

Where:

Show Query Builder Allows you to browse database structure, search for objects (routines,
definitions)

Show myDBR Commands Quick access to myDBR commands and command options and to command
help

Show selected object Select database object from code and click this to see the code/definition of
the selected database object. The object will be opened in a new tab

Execute Execute selected text or if no text is selected, the full code from the editor
window. When multiple queries are included in the editor, the editor uses
separator ('$$' in MySQL, 'go' in other databases) to separate multiple
commands from each other.

Show results in new window By default the results from executed queries are shown under the editor. If
this option is selected the output is shown in a separate window.

296
myDBR SQL Editor

Output as SQL This option formats the output of the query as SQL into a new window. This
option allows you to send troubleshoot report to myDBR support without the
need to have a table structure and all the data to be sent. The SQL output
is enough to replicate a troublesome report.

/* */ Comment selected section of the code

History/ Saves executed commands and procedures in case you lose on. Will be kept
in session and cleared in logout.

History Saves executed commands and procedures in case you lose on. Will be kept
in session and cleared in logout.

Code-snippets Code snippets palette for default and user defined snippets. If editor has
selection, button will create a new snippet based on the selection.

Keyboard shortcuts Show Keyboard shortcuts

Set editor theme, indent, keymap and autocomplete databases.


Preferences

Tabs: Original, Editing, Query While developing the reports you can have helper code to be executed from
1 a different tab. The Original tab contains the source code as it was before
you started editing

The editor can be started from a number of points:

• For existing reports:

• Select 'report code' from the main screen.

• Select Edit report code from the 'Edit Report' screen.

• Select

'Edit report code' from report Wizard.

• For new reports:

• Select 'Add report' from the main screen. You will now be asked for the name of the stored procedure to
be created.

Query Builder
Query Builder will help you browse the database and create basic queries. You can select data from multiple
tables / databases and Query Builder will create the SQL for you. Query Builder relies on FOREIGN KEY's in
the database to automate the join's between multiple tables. Query Builder will be visible by default when a new
report is created. For old reports simply push 'Show Query Builder'

Query Builder is designed to speed up report creation by automating the most tedious parts of query building:
remembering tables and columns, and relations between the columns.

Query Builder consist of four views of the database. The first view lists all databases visible to the user. The
second view lists tables in selected database and third view lists columns in selected table. The final view is
for the user query columns.

Building a query
Select the columns you wish to be part of the query. You can select columns freely from different tables and
databases.

297
myDBR SQL Editor

Once the columns are selected, you can re-arrange the columns and select aggregate functions used by the
query. When you have completed the column selection you can generate the SQL command by pushing either
of the 'Generate SQL'-buttons. 'Generate SQL into selection'-button will place the generated SQL code to the
editor's current window at the insertion caret's position. 'Generate SQL into new tab' will generate a new tab
and place the code there.

Generated SQL:

select c.name as 'Name',


p.name as 'Name',
sum(pr.amount) as 'Amount'
from acre.Company c, acre.Product p, acre.Production pr
where c.id = pr.company_id and p.id = pr.product_id
group by c.name, p.name;

Note
Please note that if your database has not defined the foreign key constraints no joins will generated
(where clause is 1=1). You can either create the foreign keys for tables or if you cannot change the
database, define the relations to myDBR's 'mydbr_key_column_usage' table.

myDBR Commands
myDBR Commands offers a summary of all the available myDBR commands. The commands are categorized
or you can view them in one list. You can search the commands via the search box up from the command list.
A command can be inserted into the current editing point by clicking the 'Insert command into selection'-button
or by double clicking the command line. A direct link to myDBR's help is provided for each command.

Using SQL Editor


When you first start the editor, the following tabs will be available:

Original When editing an existing stored procedure, this tabs contains the source code as it was before you
started editing. This is useful for restoring the original version of the source code in cases where
you want to revert back the original code.

298
myDBR SQL Editor

Editing The source code of the stored procedure.

Query 1 This is used for executing additional SQL statements. Usually you would call the stored procedure
from here. If needed you can add more tabs by clicking '+'. Click '-' to remove unnecessary ones.

Executing statements
When you click Execute, the SQL code of the currently visible tab will be executed. You can also execute just
part of the code simply selecting part of the script and clicking Execute. You will see the results and possible
error messages on the lower part of the page. You execute multiple statements at once by adding a command
delimiter between the commands. The delimiter for MySQL is '$$' and 'go' for MS SQL Server, Sybase ASE
and SQL Anywhere.

Getting code for additional objects


When you create myDBR reports, you often call other procedures, functions or want to see table definition. If
you highlight a procedure name, function name or a table name and click Show Object, you will get the source
code/table definition in a new tab. This allows you to see parameters / table definitions you might need in the
report making.

Using autocomplete
Select the databases whose structure you wish to autocomplete from editor preferences. Type start of the object/
column name and use Ctrl (Cmd on Mac) - Space to bring up the autocomplete suggestions-

Tip
You can have a separate window for SQL Editor open and run the report on another window while you
work. This way you will see the changes immediately after the browser refreshes.

Output as SQL
This option formats the output of the query as SQL into a new window. This option allows you to send
troubleshooting reports to myDBR support without need to have table structure and all data to be sent. The SQL
output is enough to replicate the troublesome report.

To use the option, open the report in question in SQL Editor and check the report parameters:

299
myDBR SQL Editor

Go to "Query 1"-tab and fill in the parameters you wish to use and check the "Output as SQL"-checkbox. Now
when you click the "Execute"-button, the report procedure is executed and the output is translated to SQL.

The SQL-output is put into a new "SQL"-tab, where you can copy it to a text document and send to myDBR
support. After this the support team will be able to execute exactly same report without your table and data
structure.

Code snippets
myDBR comes with pre-defined code snippets you can use to speed up your report writing. You can create new
ones and attach keybord shortcuts to the snippets.

To create a new code snippet, select a text in the editor and click the 'Code snippet' button. If no text is selected,
the button brings up the palette.

300
myDBR SQL Editor

To insert a snippet code to the editor, click the snippet and the text will be inserted at caret in the editor.

Cursor position after the insert can be set by clicking the move cursor icon (

). The movement is defined as movement right and down from the caret position.

Keyboard shortcuts
The default key map is described below. If you are using Mac, use Cmd instead of Ctrl.

Keycode Action
Ctrl-A Select all
Ctrl-Home Go to the start of the document
Ctrl-Left Go to stat of the line
Ctrl-Backspace Delete to beginning of line
Ctrl-F Find
Ctrl-G Find next
Ctrl-U Undo selection

301
myDBR SQL Editor

Ctrl-Alt-F Search / Replace


Alt-F Go to word right
Ctrl-V Page down
Alt-D Delete world right
Ctrl-Space Autocomplete
Tab Indent more
Shift-Tab Indent less
Esc Exit full screen
Ctrl-S Save to a local file
Ctrl-E Execute SQL
Ctrl-M (Sublime Text Ctrl-Alt-M), same in Mac Insert myDBR command

Macros
Simple macros can be defined in mydbr/user/defaults.php. Following macros have been defined in mydbr/
defaults.php

Keycode Action
Ctrl-Alt-S select-clause
Ctrl-I if-clause
Ctrl-Alt-I if-else-clause
Ctrl-Alt-W while-clause

Autocomplete table columns


The editor performs autocompletion to complete the SQL table / view columns. To take advantage of this, use
the editor preferences mark the databases which are to be autocompleted. To get the suggestions, create first
select query with a from-clause and use either the table name or the table alias in the select-line.

302
Appendix A. MySQL Stored Procedures
MySQL, like Microsoft SQL Server and Sybase, includes server side routines called stored procedures (and
functions). Stored procedures allow additional programming logic to be included in queries while maintaining
good performance.

While stored procedures include full elements of structured programming, you should always consider that SQL
databases work best when used using set operations. Beware that even if the things like loop structures exists
in stored procedures, you should avoid serializing database operations. In most of the cases things like loops
can be avoided by using well written queries and/or temporary tables.

If you are unfamiliar with stored procedures one good way to start is by reading through MySQL 5.0 Stored
Procedures an excellent "sA MySQL® Technical White Paper" by Peter Gulutzan.

Using parameters
Stored procedure without parameters
If your stored procedure does not have any parameters, create the procedure with nothing inside braces.

delimiter $$
drop procedure if exists sp_DBR_hello_world$$
create procedure sp_DBR_hello_world()
begin

select 'hello world!';

end
$$

mysql> call sp_DBR_hello_world();


+--------------+
| Hello World! |
+--------------+
| Hello World! |
+--------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Stored procedure with parameters


When you have parameters, use a comma separated "variablename datatype" definition inside the parentheses.
It is good practice to differentiate the parameters with a prefix (here 'in_') so the parameters are not conflicting
with column names and procedure code will be easier to read.

delimiter
$$
drop procedure if exists sp_DBR_show_value$$
create procedure sp_DBR_show_value( in_value int )
begin

select concat( 'value is ', invalue);

end

303
MySQL Stored Procedures

$$

mysql> call sp_DBR_show_value(1971);


+-------------------+
| Value |
+-------------------+
| The value is 1971 |
+-------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Using Variables
With using variables you can add logic to your procedures. Variables needs to be declared and typed before
use. It is good practice to differentiate the variables with a prefix (here 'v_') so the variables are not conflicting
with column names and the report code will be easier to read.

delimiter
$$
drop procedure if exists sp_DBR_variables
$$
create procedure sp_DBR_variables()
begin

declare v_value integer;


declare v_date date;

set v_value = 1;
set v_date = now();

select v_value as 'Value', v_date as 'Date';

end
$$

mysql> CALL sp_DBR_variables();


+-------+------------+
| Value | Date |
+-------+------------+
| 1 | 2015-03-27 |
+-------+------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected, 1 warning (0.00 sec)

Using Conditions
MySQL offers full range of conditional statements for your disposal. This allows logic to be placed inside the
report.

IF-THEN-ELSE

delimiter
$$
drop procedure if exists sp_DBR_who_is

304
MySQL Stored Procedures

$$
create procedure sp_DBR_who_is(
in_name varchar( 50 )
)
begin

declare vtext varchar( 100 );

if (in_name = 'sherlock') then


set vtext = concat( "mr. ", in_name, " holmes of course." );
elseif (in_name = 'holmes') then
set vtext = concat( "mr. sherlock ", in_name, " it is." );
else
set vtext = concat("who is ", in_name, "? sorry, i don't know this person.");
end if;
select vtext as 'answer';

end
$$

mysql> call sp_DBR_who_is( "Sherlock" );


+--------------------------------+
| Answer |
+--------------------------------+
| Mr. Sherlock Holmes of course. |
+--------------------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> CALL sp_DBR_who_is( "Holmes" );


+----------------------------+
| Answer |
+----------------------------+
| Mr. Sherlock Holmes it is. |
+----------------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> CALL sp_DBR_who_is( "Watson" );


+-------------------------------------------------+
| Answer |
+-------------------------------------------------+
| Who is Watson? Sorry, I don't know this person. |
+-------------------------------------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

CASE

delimiter
$$
drop procedure if exists sp_DBR_number
$$
create procedure sp_DBR_number( in_value int )
begin

case in_value
when 1 then select 'one';

305
MySQL Stored Procedures

when 2 then select 'two';


else select "sorry, can't do any better";
end case;

end
$$

mysql> call sp_DBR_number( 1 );


+-----+
| one |
+-----+
| one |
+-----+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> CALL sp_DBR_number( 2 );


+-----+
| two |
+-----+
| two |
+-----+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

mysql> call sp_DBR_number( 3 );


+----------------------------+
| Sorry, can't do any better |
+----------------------------+
| Sorry, can't do any better |
+----------------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

Using Loops
With loop statements you can add additional programmability to your reports. Be aware that you do not
accidentally serialize SQL statements when using SQL. This may have a negative impact on performance.

WHILE ... END WHILE

delimiter
$$
drop procedure if exists sp_DBR_fibonacci
$$
create procedure sp_DBR_fibonacci( in_value int )
begin

declare v_count int;


declare v_text varchar( 500 );
declare v_fn2 int default 0;
declare v_fn1 int default 1;
declare v_fn int;

set v_count = 2;
set v_text = concat(v_fn2, " ", v_fn1, " ");

306
MySQL Stored Procedures

while (v_count < in_value) do


set v_fn = v_fn2 + v_fn1;
set v_text = concat(v_text, v_fn, " " );
set v_fn2 = v_fn1;
set v_fn1 = v_fn;
set v_count = v_count + 1;
end while;

select v_text as 'fibonacci';

end
$$

mysql> call sp_DBR_fibonacci( 12 );


+-------------------------------+
| Fibonacci |
+-------------------------------+
| 0 1 1 2 3 5 8 13 21 34 55 89 |
+-------------------------------+
1 row in set (0.01 sec)

Query OK, 0 rows affected (0.01 sec)

REPEAT .. END REPEAT

delimiter
$$
drop procedure if exists sp_DBR_hellos
$$
create procedure sp_DBR_hellos()
begin

declare v_count int default 0;


declare v_text varchar( 50 ) default "";

repeat
set v_text = concat(v_text, "hello ");
set v_count = v_count + 1;
until v_count = 5 end repeat;

select v_text as 'hellos';

end
$$

mysql> call sp_DBR_hellos();


+--------------------------------+
| Hellos |
+--------------------------------+
| Hello Hello Hello Hello Hello |
+--------------------------------+
1 row in set (0.00 sec)

Query OK, 0 rows affected (0.00 sec)

LOOP .. END LOOP

307
MySQL Stored Procedures

delimiter
$$
drop procedure if exists sp_DBR_countdown
$$
create procedure sp_DBR_countdown()
begin

declare v_count int default 10;


declare v_text varchar( 100 ) default "";

my_loop_label: loop
set v_text = concat(v_text, v_count, " ");
set v_count = v_count - 1;
if v_count = 4 then
set v_text = concat(v_text, "#main engine start# ");
elseif v_count = 0 then
set v_text = concat(v_text, "#solid rocket booster ignition and liftoff#");
leave my_loop_label;
end if;

end loop;
select v_text as 'countdown ...';

end
$$

mysql> CALL sp_DBR_countdown();


+----------------------------------------------------------------------------------------+
| Countdown ... |
+----------------------------------------------------------------------------------------+
| 10 9 8 7 6 5 #Main engine start# 4 3 2 1 #Solid rocket booster ignition and liftoff#
|
+----------------------------------------------------------------------------------------+
1 row in set (0.01 sec)

Query OK, 0 rows affected (0.01 sec)

Using Temporary Tables


By using temporary tables you can store interim results within a report and further process them. Temporary
tables are connection based, so different users using temporary tables with same name do not conflict.

delimiter
$$
drop procedure if exists sp_DBR_fruits
$$
create procedure sp_DBR_fruits()
begin

drop temporary table if exists fruits_tmp;


create temporary table fruits_tmp ( fruit varchar(30) ):

insert into fruits_tmp (fruit)


select 'banana'
union
select 'orange'
union
select 'lemon';

308
MySQL Stored Procedures

insert into fruits_tmp (fruit)


values( 'apple' );

select count(*) as 'fruits' from fruits_tmp;


drop temporary table fruits_tmp;

end
$$

mysql> CALL sp_DBR_fruits();


+--------+
| Fruits |
+--------+
| 4 |
+--------+
1 row in set (0.00 sec)

309
Appendix B. Command reference
Aggregate functions

dbr.sum - Calculates the sum of the selected column


dbr.min - Calculates the minimum value of the selected column
dbr.max - Calculates the maximum value of the selected column
dbr.count - Calculates the number of rows
dbr.avg - Calculates the average of selected column
dbr.sum.prefix - Set's the prefix to be used with dbr.sum
dbr.min.prefix - Set's the prefix to be used with dbr.min
dbr.max.prefix - Set's the prefix to be used with dbr.max
dbr.count.prefix - Set's the prefix to be used with dbr.count
dbr.avg.prefix - Set's the prefix to be used with dbr.avg
dbr.summary.text - Adds text to summary row
dbr.calc - Allows you to create calculation formulas to populate cells
dbr.summary.calc - Same as dbr.calc. Kept for compatibility with older versions
dbr.summary.options - Change the default aggregate calculation

Titles / text

dbr.title - Set the report title. By default title is report's name


dbr.subtitle - Give a name to the result set in a report
dbr.text - Insert a free text element to report

Applying styles

dbr.hidecolumns - Hide the number of columns at the end of the result set
dbr.hidecolumn - Hide individual columns which can be anywhere in the query
dbr.showcolumn - Show individual columns that were automatically hidden
dbr.rowstyle - Report row's CSS style. A column in the query contains the CSS style for the row
dbr.rowclass - Report row's CSS class. A column in the query contains the CSS-classname for the row
dbr.colstyle - Report column's style, where a style is a combination of printf formatting/CSS-style
dbr.colclass - Report column's CSS class. Adds a CSS-class to a specified column
dbr.cellstyle - Adds CSS-style to individual cells based on style in another column. This allows value based
formatting
dbr.cellclass - Adds CSS-class to individual cells based on style in another column. This allows value
based formatting
dbr.cellformat - Report cells' printf format. Format column with formatting from another column. Allows
formatting cells differently in the same column in different rows
dbr.hideheader - Hide the headers in result set
dbr.headerstyle - Header's style
dbr.header.colclass - Header-column's CSS class
dbr.footerstyle - Footer's style
dbr.footer.colclass - Footer column's CSS class'
dbr.footer.colstyle - Footer's style for specific column
dbr.footer.cellclass - Set footer's CSS class based on data on another footer column
dbr.footer.cellstyle - Set footer's CSS style based on data on another footer column
dbr.resultclass - Add custom CSS class to result table
dbr.html5data - Put a column to another columns data-xxx attribute instead of a column

Calendar

dbr.calendar - Create a calendar from a result set or dynamically via Ajax


dbr.calendar.report - Define the Ajax report for calendar data
dbr.calendar.options - Set calendar options

310
Command reference

Cross tabulation
dbr.crosstab - Turn a table report into a cross tabulation report. The first parameter is the crosstable column,
the optional second parameter marks the last data column inside a crosstable.
dbr.hsum - Calculate horizontal sum in a cross tabulation report
dbr.hmin - Calculate horizontal minimum in a cross tabulation report
dbr.hmax - Calculate horizontal maximum in a cross tabulation report
dbr.hminus - Calculate horizontal value with formula Col1 - Col2 - Col3...
dbr.hnull - Creates a placeholder for horizontal column used with dbr.calc
dbr.hcount - Calculate number of values horizontally in a cross tabulation report
dbr.havg - Calculate horizontal average in a cross tabulation report
dbr.hidecolumn.data - Allows hiding crosstable data columns, keep summary column. Used with dbr.calc
dbr.hidecolumn.set.data - Allows hiding crosstable data columns based on data CrossTabSet name
dbr.hidedatacolumn - Same as dbr.hidecolumn.data, kept for compatibility
dbr.hidecolumn.data.all - Hide all crosstable data columns, keep summary column.
dbr.hidecolumn.summary - Allows hiding crosstable summary columns, keeping data columns. . Used with
dbr.calc
dbr.crosstab.title - Redefine the default title for horizontal summary column
dbr.crosstab.order - Set the order of the cross tabulation columns
dbr.crosstab.col - Predefine the cross tabulation columns
dbr.crosstab.options - Add crosstab option
dbr.crosstab.col.title - Set column title for crosstab horizontal summary column
dbr.crosstab.col.style - Set columnstyle for crosstab horizontal summary column
dbr.crosstab.header - Add additional header group in crosstab
dbr.crosstab.header.col - Predefine the 2nd level cross tabulation header columns defined in
dbr.crosstab.header

Header levels
dbr.hdr - Set header level in a query
dbr.hdr.options - Do not hide repeating headers

Appearance
dbr.accordion - Organize report elements with accordions
dbr.accordion.close - Marks the end of an accordion
dbr.accordion.class - Define your own accordion style with a class
dbr.accordion.style - Define your own accordion style
dbr.column.filter - Add a client side filter for a column
dbr.column.title - Define the title for a column in cases where the content of the column is dynamic
dbr.collapse - Collapse selected columns to make more compact view
dbr.colsort - Alias for dbr.sortcol
dbr.compare - Show database results side by side
dbr.compare.options - Change compapare behavior
dbr.divify - Use DIV's instead of tables in output
dbr.header.group - Add additional header row in order to group columns
dbr.keepwithnext - Makes next element to be placed side by side with the current one
dbr.lockcolumns - Lock leftmost columns when resultset does not fit into the screen
dbr.no_data - Define a placeholder for queries that do not return any data
dbr.nosort - Disable sorting on specified columns
dbr.parameters.show - Make parameter input visible in report
dbr.pageview - Show a row from the database in a page view
dbr.refresh - Make report automatically refresh itself at a given interval or just once if no parameters are given
dbr.resultset.options - Allows combining multiple result sets by skipping header/footer
dbr.rownum - myDBR replaces the command with the row number in the result set
dbr.rownum.set - Initialize the rownum-value
dbr.search - Disable/enable search & export for a given result set
dbr.scrollable - Make result set scrollable with fixed number of rows
dbr.sort - Set initial sorting order

311
Command reference

dbr.sortcol - Sort a column based a value from another column


dbr.sortmethod - Override the default sort method
dbr.sortorder - Override the default initial sort order. The default is 'intelligent'
dbr.sort.remember - Remember user's sort order
dbr.header.tooltip - Define tooltip for the header
dbr.tooltip - Define cell's tooltip
dbr.pager - Attach the pager component to a table report
dbr.tab - Organize report elements with tabs
dbr.tab.class - Define your own tab style with class
dbr.tab.close - Mark the tab element as closed
dbr.tab.next - Switch to next unpopulated tab
dbr.tab.selected - Set's the default tab by name or by tab order number (0=first, 1=second)
dbr.tab.style - Define your own tab style

Charts
dbr.chart - Create a chart from the following result set
dbr.chart.color - Set chart colors
dbr.chart.options - Specify chart options
dbr.chart.gv.option - Specify GraphViz chart options
dbr.chart.gv.style - Defines the default style for the object
dbr.chart.gv.node - Defines the individual node style
dbr.chart.gv.cluster - Defines the individual cluster style
dbr.chart.gv.engine - Selects the layout engine
dbr.chart.gv.renderer_formatter - Selects the renderer and optional formatter for the engine overriding
the default ones, for example cairo:cairo

Linked reports
dbr.report - Create a link to another report
dbr.url - Create a link to an external URL
dbr.button - Create a button containing a link
dbr.list - Create a list containing a link to a report
dbr.embed_object - Create a placeholder or a popup window for linked report's content
dbr.selectlist - Create a select list for linked reports
dbr.searchable - Create a search field to get dynamic content

Editable reports
dbr.editable - Prepares a column so it is in-place editable
dbr.upload - Upload a file to the server's filesystem
dbr.upload.options - Set an upload option
dbr.selectable - Convert an integer ID column to a selectable row to be used with a report linked button

Passing HTML into the page


dbr.html - Pass HTML directly into the report
dbr.purehtml - Same as dbr.html, kept for compatibility
dbr.html: - Include HTML into a string
dbr.purehtml: - Same as dbr.html:, kept for compatibility
dbr.javascript - Include Javascript code in the report
dbr.css - Include CSS definitions in the report
dbr.head - Include tags into HTML head part

Templates
dbr.template - Defines a template being used for the subsequent result set

Running total
dbr.running_total - Calculate running total for a column

312
Command reference

Import commands
dbr.import.prepare - Before the import is done, this preparation report is run
dbr.import.finish - After the import is finished, this report is run
dbr.import - This procedure is called for each import row
dbr.import.options - Set import options

Export commands
dbr.export.options - Set export option
dbr.wkhtmltopdf - Pass command line parameters to wkhtmltopdf command
dbr.calc.excel - Define an Excel native formula for a column
dbr.blob - Read file from database

Remote calls to other myDBR servers


dbr.remote.prepare - Defines the server to be called, call to be made and local table to receive the results.
Required, needs to be called before 'dbr.remote.call'
dbr.remote.call - Executes the defined remote call and runs local report to handle the results. Required.
dbr.remote.options - Allows setting extra options for transfer. Option includes to turn off certificate check
on remote server. Optional and needs to be called before 'dbr.remote.prepare'.

Google Maps extension


dbr.googlemaps - Display Google Maps mashup
dbr.googlemaps.heatmap - Use Google Maps Heatmap layer
dbr.googlemaps.link_in_title - Whether to show single linked report in title or in the marker
dbr.googlemaps.polyline - Draw a polyline between the points
dbr.googlemaps.route - Draw route between the points
dbr.googlemaps.kml - Include KML-file into the maps
dbr.googlemaps.geojson - Include GeoJSON-file into the maps

OpenStreetMap extension
dbr.openstreetmap - Show OpenStreetMap
dbr.openstreetmap.heatmap - Use OpenStreetMap layer
dbr.openstreetmap.tiles - Use alternative tiles on top of OpenStreetMap
dbr.openstreetmap.geojson - Include GeoJSON-file into the maps

Mail extension
dbr.mail - Send mail
dbr.mail.sender - Provide sender address in the report instead of using the one from the settings (user/
extension_init.php)
dbr.mail.recipient - Add multiple recipients to the mail to be sent
dbr.record - Record report output for mail delivery or to be used with a template
dbr.mail.attach - Add attachment to mail
dbr.mail.notify_successful_mail - Disable the "Mail sent" message
dbr.mail.smtp.user - Use alternate SMTP user/password
dbr.mail.smtp.server - Use alternate SMTP server
dbr.mail.smtp.authentication.type - Select SMTP authentication (default LOGIN)
dbr.mail.smtp.nlmt.realm - Realm for NTLM authentication type
dbr.mail.smtp.nlmt.workstation - Workstation for NTLM authentication type
dbr.mail.encoding - Set the mail encoding ("8bit", "7bit", "binary", "base64" and "quoted-printable")
dbr.mail.debug - Set debug on to get verbose error messages (1=debug on,0=debug off)
dbr.mail.log.proc - Define a procedure which will log the mail actions.
dbr.mail.nobr.html - Do no convert linefeeds to line breaks in HTML mail

Push Notification extension


dbr.push - Send a push message

313
Command reference

dbr.push.sender - Choose another sender than the one defined in $mydbr_push init
dbr.push.option - Set a service specific option
dbr.push.notify_successful_push - Disable the "Push message sent" message
dbr.push.log.proc - Log the push message activity to database
dbr.push.debug - Show status for each message sent

eChart extension

dbr.echart - Create an extended chart


dbr.echart.color - Select colors for the chart
dbr.echart.name - Select category names
dbr.echart.bubble_scale - Scale bubble chart axis

d3 extension

dbr.d3 - Create a d3 object


dbr.d3.sankey_format - Format the Sankey tooltips
dbr.d3.zoom - Zoom the chord diagram when data has long texts

SMS extension

dbr.sms - Send SMS


dbr.sms.sender - Provide a sender ID for the outgoing message. Note: Sender ID's need to be requested
and approved from Clickatell before they can be used.

Organization chart extension

dbr.org.chart - Display organization chart


dbr.org.chart.export - Show "Export as PNG" button in the chart
dbr.org.target - Add a target to the node

Barcode extension

dbr.barcode - Show the barcode

QR code extension

dbr.qrcode - Show the QR code

314

Das könnte Ihnen auch gefallen