PHP Classes

File: demo3-classpersistence.php

Recommend this page to a friend!
  Classes of Bob Gombocki   PersistClass   demo3-classpersistence.php   Download  
File: demo3-classpersistence.php
Role: Example script
Content type: text/plain
Description: Object mapping
Class: PersistClass
DB access wrapper & storing objects in DB tables
Author: By
Last change:
added web tutorial info
Date: 13 years ago
Size: 2,675 bytes


Class file image Download

    for updates, documentation, tutorials

// connect to database (executing demo 1)

// preparation for the demo (inserting a row with id = 1)
$con = DbConnectionPool::instance()->getConnection();
$con->query('delete from testtable where testid = 1');
$con->query('insert into testtable(testid, testcolumn) values(1, "blabla")');

// create class for test table
class TestTable extends PersistClass {
$sqlTableName = 'TESTTABLE';
$sqlPrimaryKey = 'testid';

// retrieving a class containing row with primary key = 1
$id = 1;
$testRecord = new TestTable($id);
// OR
//$testRecord = new TestTable();

// get data from columns
$testColumn = $testRecord->getData('testcolumn');
$otherTestColumn = $testRecord->getData('othertestcolumn');

// set data in columns (only sets in class at this point)
$testRecord->setData('testcolumn', 'SUCCESSFULLY CHANGED');
$testRecord->setData('othertestcolumn', 'Any number of columns can be set');

// save changes to the database

// delete record

// insert new record (the setNewData method needs to be used in this case)
$newTestRecord = new TestTable();
$newTestRecord->setNewData('testcolumn', 'INSERT SUCCESS!');
$newTestRecord->setNewData('othertestcolumn', 'This column is set too');
// or initialize using an array:
// arr = array('testcolumn' => 'INSERT SUCCESS!', 'othertestcolumn' => 'This column is set too');
// $newTestRecord = new TestTable($arr);

// getting id of inserted record

// disable db input escaping to allow DB functions to be executed
$newTestRecord->setNewData('testcolumn', 'NOW()', false);

// retrieving all rows
$test = new TestTable();
$allTestRecords = $test->getAllItems();

// retrieving rows with ids
$sql = 'select testid from TESTTABLE where testcolumn = "im looking for rows containing this value"';
$ids = DbConnectionPool::instance()->getConnection()->queryFirstColumnSet($sql);
$test = new TestTable();
$testRecordsWithIds = $test->getItemsWithIds($ids);

// retrieving all rows with where statement
$test = new TestTable();
$tests = $test->getAllItems("where testcolumn='im looking for rows containing this value'");

// retrieving all rows with where statement ordered by testid
$test = new TestTable();
$tests = $test->getAllItems("where testcolumn='im looking for rows containing this value' order by testid");

'Test successful'