When building a plugin, a lot of times we want to store data for various purposes. Database is the heart of building a dynamic application where data is being manipulated based on user action. Data could be stored, retrieved and manipulated through a central storage system powered by PageCarton Database Tables.
Creating a Database Table
The process of creating Database Tables is similar albeit a lot easier than widgets.
PageCarton Admin Panel > Plugins > My Plugins > "New DB Table"
Unlike the widget, customizing the Database Table after creation is not required. After entering the class name and database fields, and data types, the Class file is created automatically and the Database tables can be used immediately. Database Tables are mostly used in Widgets through API calls.
Database Table APIs
In other to demonstrate the usage of the Database Table APIs, we will be using a hypothetical table with class name 'My_First_Widget_Table'. It stores user comments using field names 'first_name', 'email_address' and 'comment'. All the field names have 'TEXT' datatypes. Usage of some of the APIs are illustrated below:
Instantiating the Database Table
$table = new My_First_Widget_Table();
Writing to Database
$record1 = array( 'first_name' => 'John', 'email_address' => 'email@example.com', 'comment' => 'This site is cool' );
$table->insert( $record1 );
$record2 = array( 'first_name' => 'Ade', 'email_address' => 'firstname.lastname@example.org', 'comment' => 'Nice and smooth' );
$table->insert( $record2 );
Retrieving Data from Table
// Seek rows for comments by "John"
$where = array( 'first_name' => 'John' );
$rows = $table->select( null, $where );
var_dump( $rows );
// outputs array( 0 => array( 'first_name' => 'John', 'email_address' => 'email@example.com', 'comment' => 'This site is cool' ) );
$table->update( $newRecordValues, $where );
$table->delete( $where );