Basic Usage
Вернуться к: MDB2_TableBrowser
Basic Usage
Steps to creating a table object out of your database table or view. This example connects to a mysql database animal_db and constructs a table object from the tbl_animals table.
Create an MDB2 object:
<?php
require_once "MDB2.php";
$dsn = 'mysql://username:pass@localhost/animal_db';
$mdb2 = MDB2::singleton($dsn);
?>
Load the TableBrowser extention:
<?php
$mdb2->loadModule('TableBrowser');
?>
Create the table object Create a table browser for the tbl_animals table, and specify id as the primary key:
<?php
$browser = $mdb2->tableBrowserFactory('tbl_animals', 'id');
?>
Retreiving Data
A table object allows you several ways of retrieving data from the underlying table. The examples below continue from the animals_db database.
Retrieving a single row is done via the getRows method. This call returns the row data as a hash array:
<?php
$browser->getRow(1);
?>
Retrieving multiple rows is done via the getRows method. This call returns an MDB2_Results object. From the animals db example... Get data the 3 animals in the table sorted by name starting with the 5th animal
<?php
$browser->getRows('name', 3, 5);
?>
Retrieving the different values in a column has is done via the getColumnValues method. In our example, we can get the different kinds of animals in tbl_animals eg: mammal, reptile,...
<?php
$browser->getColumnValues('type');
?>
Inserting
Inserting a single row is done via insertRow method. It takes a single hash array as input.
<?php
$rowData = array('id'=>13, 'name' => 'duck','type' => 'bird','lifespan' => 5);
$browser->insertRow($rowData);
?>
Inserting multiple rows at once is done via insertRows method.
<?php
$data = array(
array(1,'dog','mammal',12),
array(2,'cat','mammal',30),
array(3,'parrot','bird',60),
array(4,'shark','fish',30),
array(5,'dolphin','mammal',50),
array(6,'crocodile','reptile',50),
array(7,'snake','reptile',20),
array(8,'spider','arachnid',1),
array(9,'housefly','insect',1),
array(10,'ostrich','bird',35),
array(11,'bat','mammal',6),
array(12,'human','mammal',100)
);
$browser->insertRows(array('id', 'name','type','lifespan'), $data);
?>
Updating
Updating a single row is done via updateRow method.
<?php
//Get the row data
$rowData = $browser->getRow(3);
//Modify the data
$rowData['lifespan'] = 65;
//Update the row
$browser->updateRow(3, $rowData);
?>
Вернуться к: MDB2_TableBrowser