Location: PHPKode > scripts > Persist Class > persist-class/demo3-classpersistence.php

// 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 {
	protected $sqlTableName = 'TESTTABLE';
	protected $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
$con = DbConnectionPool::instance()->getConnection();
$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);

echo 'Test successful'

Return current item: Persist Class