Home » Database » MDB_QueryTool » Manual
This package is an OO-abstraction to the SQL-Query language, it provides methods such as setWhere, setOrder, setGroup, setJoin, etc. to easily build queries.
Introduction
Introduction – An OO-interface for easily retrieving and modifying data in a database
MDB_QueryTool Description
This package is an OO-abstraction to the SQL-Query language, it provides methods such as setWhere(), setOrder(), setGroup(), setJoin(), etc. to easily build queries. It also provides an easy to learn interface that interacts nicely with HTML-forms using arrays that contain the column data, that shall be updated/added in a database. This package bases on an SQL-Builder which lets you easily build SQL-Statements and execute them. It supports all the db engines supported by MDB and MDB2.
Since it's a 1:1 port of DB_QueryTool, it has the same API, the only difference being the class name (and the constructor name, of course). Unfortunately, complete documentation is not available at the moment.
Example 1 - Arrays
The best way to use MDB_QueryTool is creating a class that extends it. Here's a sample usage:
<?php
require_once 'MDB/QueryTool.php';
define('TABLE_CARS', 'cars');
$dsn = 'mysql://user:pass@host/dbname';
/**
* Let's suppose the "car" table has the following fields:
* (id, model, hp, color, clima, price)
*/
class Car extends MDB_QueryTool
{
var $table = TABLE_CARS;
var $sequenceName = TABLE_CARS;
// this is default, but to demonstrate it here ...
var $primaryCol = 'id';
/**
* This table spec assigns a short name to a table name
* this short name is needed in case the table name changes
* i.e. when u put the application on a provider's db, where you have to
* prefix each table, and you dont need to change the entire application to
* where you refer to joined table columns, for that joined results the
* short name is used instead of the table name
*/
var $tableSpec = array(
array('name' => TABLE_CARS, 'shortName' => 'cars'),
//array('name' => TABLE_TIME, 'shortName' => 'time'),
);
}
//instanciate an object of the Car class
$car = new Car($dsn);
//get the car #3
$car->reset(); // reset the query-builder, so no where, order, etc. are set
$res = $car->get(3);
var_dump($res);
//get all the cars
$car->reset(); // reset the query-builder, so no where, order, etc. are set
$res = $car->getAll();
var_dump($res);
// get the first 10 cars
$car->reset(); // reset the query-builder, so no where, order, etc. are set
$res = $car->getAll(0, 10);
var_dump($res);
//get all the red cars with clima, sorted by price
$car->reset();
$car->setWhere('color="red"');
$car->addWhere('clima=1');
$car->setOrder('price');
$res = $car->getAll();
var_dump($res);
//add a new car to the database
$data = array(
'model' => 'Super Trooper',
'hp' => 140,
'color' => 'black',
'clima' => 0,
'price' => 19000
);
$newCarId = $car->save($data);
var_dump($newCarId);
//update an existing car
$data = array(
'id' => $newCarId,
'clima' => 1,
'price' => 20000,
);
$res = $car->save($data); //equivalent to $car->update($data);
var_dump($res);
//remove the car from the database
$res = $car->remove($newCarId);
var_dump($res);
?>
Example 2 - Classes
MDB_QueryTool also offers working with classes. Here's a sample usage:
<?php
require_once 'MDB/QueryTool.php';
define('TABLE_CARS', 'cars');
$dsn = 'mysql://user:pass@host/dbname';
/**
* Let's suppose the "car" table has the following fields:
* (id, model, hp, color, clima, price)
*/
class Car extends MDB_QueryTool
{
var $table = TABLE_CARS;
var $sequenceName = TABLE_CARS;
// this is default, but to demonstrate it here ...
var $primaryCol = 'id';
/**
* This table spec assigns a short name to a table name
* this short name is needed in case the table name changes
* i.e. when u put the application on a provider's db, where you have to
* prefix each table, and you dont need to change the entire application to
* where you refer to joined table columns, for that joined results the
* short name is used instead of the table name
*/
var $tableSpec = array(
array('name' => TABLE_CARS, 'shortName' => 'cars'),
//array('name' => TABLE_TIME, 'shortName' => 'time'),
);
}
//instanciate an object of the Car class
$car = new Car($dsn);
$car->useResult('object');
//get the car #3
$car->reset(); // reset the query-builder, so no where, order, etc. are set
$res = $car->get(3)->fetchRow();
var_dump($res);
//get all the cars
$car->reset(); // reset the query-builder, so no where, order, etc. are set
$cars = $car->getAll();
while ($res = $cars->getNext()) {
var_dump($res);
}
// get the first 10 cars
$car->reset(); // reset the query-builder, so no where, order, etc. are set
$cars = $car->getAll(0, 10);
while ($res = $cars->getNext()) {
var_dump($res);
}
//get all the red cars with clima, sorted by price
$car->reset();
$car->setWhere('color="red"');
$car->addWhere('clima=1');
$car->setOrder('price');
$cars = $car->getAll();
while ($res = $cars->getNext()) {
var_dump($res);
}
//add a new car to the database
$newCar = $car->newEntity();
$newCar->model = 'Super Trooper';
$newCar->hp = 140;
$newCar->color = 'black';
$newCar->clima = 0;
$newCar->price = 19000;
$newCarId = $newCar->save();
var_dump($newCarId);
//update an existing car
$car->reset();
$res = $car->get($newCarId)->fetchRow();
$res->clima = 1;
$res->price = 20000;
$res->save();
var_dump($res);
//remove the car from the database
$car->reset();
$res = $car->get($newCarId)->fetchRow();
var_dump($res->remove());
unset($res);
?>
Object
Object – An introduction to the usage of Objects with MDB_QueryTool
MDB_QueryTool Object Description
It is possible to use objects as result. A comprehensive example may be seen in the intro.
But using objects is not a simple alternative to using arrays as result. It is also possible to register a custom Class to be returned instead of the default MDB_QueryTool_Result_Row. The new resulting class has to be child of the MDB_QueryTool_Result_Row class.
Example 1 - Change the default result class
To change the resulting class the method setReturnClass
is used.
<?php
require_once 'MDB/QueryTool.php';
require_once 'MDB/QueryTool/Result/Object.php';
define('TABLE_CARS', 'cars');
$dsn = 'mysql://user:pass@host/dbname';
/**
* Let's suppose the "cars" table has the following fields:
* (id, model, hp, color, clima, price)
*/
class Car extends MDB_QueryTool
{
public $table = TABLE_CARS;
}
class CarEntity extends MDB_QueryTool_Result_Row
{
}
//instanciate an object of the Car class
$car = new Car($dsn);
$car->useResult('object');
$car->setReturnClass('CarEntity');
?>
Controlling class variable access
This can now be used to implement getter and setter and thus regulate the accessability to the values. In order to block the access to the class variables from outside they have to be declared as protected. Declaring them as private would result in also blocking the parent class, which gets the data, of accessing them. Of course when doing so corresponding methods have to be implemented to access the variables again.
Example 2 - Restricting class variable access
To keep the example short only methods for dealing with model, hp and clima have been implemented.
<?php
require_once 'MDB/QueryTool.php';
require_once 'MDB/QueryTool/Result/Object.php';
define('TABLE_CARS', 'cars');
$dsn = 'mysql://user:pass@host/dbname';
/**
* Let's suppose the "cars" table has the following fields:
* (id, model, hp, color, clima, price)
*/
class Car extends MDB_QueryTool
{
public $table = TABLE_CARS;
}
class CarEntity extends MDB_QueryTool_Result_Row
{
protected $id;
protected $model;
protected $hp;
protected $color;
protected $clima;
protected $price;
public function getModel() {
return $this->model;
}
public function setModel($model) {
$this->model = $model;
}
public function getHp() {
return $this->hp;
}
public function setHp($hp) {
$this->hp = $hp;
}
public function getClima() {
if ($this->clima) {
return true;
} else {
return false;
}
}
public function setClima($clima) {
if ($clima) {
$this->clima = 1;
} else {
$this->clima = 0;
}
}
}
//instantiate an object of the Car class
$car = new Car($dsn);
$car->useResult('object');
$car->setReturnClass('CarEntity');
?>
Outlook
This example only demonstrates a very basic feature. But it enables for example the implementation of Decorators. Every feature of modern OOP is now possible to implement.
Quick API reference
Quick API reference – A quick overview of the available methods. Please refer to the full API docs for a detailed documentation.
MDB_QueryTool available methods
MDB_QueryTool provides the following methods:
- autoJoin() Join the given tables, using the column names, to find out how to join the tables; i.e., if table1 has a column named "table2_id", this method will join "WHERE table1.table2_id=table2.id". All joins made here are only concatenated via AND.
- getDbInstance() Return a PEAR::DB object
- setDbInstance() Pass an existing PEAR::DB object to MDB_QueryTool
- get($id, $column) Get the data of a single entry. If the second parameter is only one column, the result will be returned directly, not as an array!
- getMultiple($ids, $column) Same as get(), but for all the elements in the $ids array.
- getAll() Get all the entries from the db.
-
getCol($column)
This method only returns one column, so the result will be a one dimensional array.
This does also mean that using setSelect() should be set
to *one* column, the one you want to have returned.
A common use case for this could be:
so ids will be an array with all the id's.<?php $table->setSelect('id'); $ids = $table->getCol(); //OR $ids = $table->getCol('id'); ?> - getCount() Get the number of entries.
- getDefaultValues() return an empty element where all the array elements do already exist corresponding to the columns in the DB
- getQueryString() Render the current query and return it as a string.
- save($data) Save data, calls either update() or add(). If the primaryCol is given in the data this method knows that the data passed to it are meant to be updated (call update()), otherwise it will call the method add(). If you don't like this behaviour simply stick with the methods add() and update() and ignore this one here. This method is very useful when you have validation checks that have to be done for both adding and updating, then you can simply overwrite this method and do the checks in here, and both cases will be validated first.
- update($data) Update the member data of a data set.
- add($data) Add a new member in the db.
- addMultiple($data) Adds multiple new members in the db.
-
remove($data, $whereCol)
Removes a member from the db.
datais the value of the column that shall be removed (integer/string); if an array is used, it must contain multiple columns that shall be matched (in this case, the second parameter will be ignored);$whereCol: the column to match the data against, only ifdatais not an array - removeAll() Empty a table.
-
removeMultiple($ids, $colName)
Remove the datasets with the given ids. If
colNameis set, it is used as the primary key column name. - removePrimary($ids, $colName, $atLeastOneObject) Removes a member from the db and calls the remove() methods of the given objects so all rows in another table that refer to this table are erased too.
- setLimit($from=0, $count=0) Set the limits for the following query.
- getLimit() Get the limits for the following query.
- setWhere($whereCondition) Sets the where condition which is used for the current instance.
- getWhere() Gets the where condition which is used for the current instance.
-
addWhere($whereCondition, $condition)
Adds a string to the where clause. The default
conditionis AND. -
addWhereSearch($column, $stringToSearch, $condition)
Add a where-like clause which works like a search for the given string;
i.e. calling it like this:
produces a where clause like this one<?php $this->addWhereSearch('name', 'otto hans') ?>UPPER(name) LIKE "%OTTO%HANS%"
so the search finds the given string. - setOrder($orderCondition, $desc=FALSE) Sets the order condition which is used for the current instance.
- getOrder() Gets the order condition which is used for the current instance.
- addOrder($orderCondition, $desc=FALSE) Adds an order parameter to the query.
- setHaving($havingCondition) Sets the having condition which is used for the current instance.
- getHaving() Gets the having condition which is used for the current instance.
- addHaving($what, $connectString) Adds an having parameter to the query.
- setJoin($table, $where, $joinType) Sets the join condition which is used for the current instance.
- setLeftJoin($table, $where) Sets a left join on $this->table.
- addLeftJoin($table, $where, $type) Adds a left join to the query.
- setRightJoin($table, $where) Sets a right join on $this->table.
- getJoin($what) Gets the join-condition.
-
addJoin($table, $where, $type)
adds a table and a where clause that shall be used for the join
instead of calling
you can also call<?php setJoin(array(table1, table2), '<where clause1> AND <where clause2>'); ?><?php setJoin(table1,'<where clause1>'); addJoin(table2,'<where clause2>'); ?> - setTable($table) Sets the table this class is currently working on.
- getTable() Gets the table this class is currently working on.
- setGroup($group) Sets the group-by condition.
- getGroup() Gets the group-by condition.
-
setSelect($what)
Limit the result to return only the columns given in
what. -
addSelect($what, $connectString)
Add a string to the select-part of the query and connects it to an existing
string using the
connectString, which by default is a comma. ("SELECT xxx FROM..." xxx is the select-part of a query) - getSelect() Gets the select-part of the query.
- setDontSelect($what) Exclude some columns from the resultset.
- getDontSelect() Gets the columns excluded from the resultset.
- reset($what) Reset all the set* settings, with no parameter given it resets them all.
- setOption($option, $value) Set mode the class shall work in. The 'raw' mode does not quote the data before building the query
- getOption($option) Get the given option.
- debug($string) override this method and i.e. print the queryString to see the final query.
- getTableShortName($table) Gets the short name for a table.
-
execute($query, $method)
Execute a query (the current query is executed when
queryis null. - writeLog($text) Write events to the logfile. It does some additional work, like time measuring etc. to see some additional info.
- returnResult($result) Return the chosen result type
-
setIndex($key)
Format the result to be indexed by
key. NOTE: be careful, when using this you should be aware, that if you use an index which's value appears multiple times you may loose data since a key can't exist multiple times! The result for a result to be indexed by a key(=columnName) (i.e. 'relationtoMe') which's values are 'brother' and 'sister' or alike normally returns this:
but if the column 'relationtoMe' contains multiple entries for 'brother' then the returned dataset will only contain one brother, since the value from the column 'relationtoMe' is used and which 'brother' you get depends on a lot of things, like the sort order, how the db saves the data, and whatever else. You can also set indexes which depend on 2 columns, simply pass the parameters like 'table1.id,table2.id' it will be used as a string for indexing the result and the index will be built using the 2 values given, so a possible index might be '1,2' or '2108,29389' this way you can access data which have 2 primary keys. Be sure to remember that the index is a string!<?php $res['brother'] = array('name' => 'xxx'); $res['sister'] = array('name' => 'xxx'); ?> - getIndex() Gets the index.
- useResult($type) Choose the type of the returned result ('array', 'object', 'none')
- setErrorCallback($param) Set both callbacks.
- setErrorLogCallback($param) Set the error log callback.
- setErrorSetCallback($param) Set the error set callback.