Inserting Database Records with a CodeIgniter PHP Framework Model - The complete source code of the generic model class
(Page 4 of 4 )
As I stated in the previous segment, in the next few lines I list the complete source code of the “AbstractModel” class, this time including the “save()” method that you learned before. Take a look at it, please:
abstract class MY_Model extends Model
{
protected $table = ''; // table associated to the model
protected $fields = array(); // fields of table associated to the model
protected $id = NULL; // value of the primary key of the table associated to the model
protected $data = array(); // model input data
protected $insertID = NULL; // insertion ID
protected $numRows = NULL; // number of rows returned by SELECTS
protected $validation = array(); // model validation rules
Definitely, the above generic model class is starting to look a bit more interesting. It's now capable of fetching rows from the specified database table, in addition to inserting new records and updating existing ones via the “save()” method. This means that almost all of the basic CRUD operations can be performed by the class in a straightforward manner, except for deletions.
Yes, it’s necessary to implement another method that allows you to delete rows from the model’s associated table, but guess what? This topic will be covered in the next tutorial, so in the meantime have fun tweaking the code in its current state.
Final thoughts
Over this fourth chapter of the series, I proceeded to code a new method for the generic model class, which allows you to insert a new records into the specified database table, as well as update an existing one. True to form, the way that this method has been implemented is pretty easy to follow, so in theory you shouldn’t have major trouble grasping its underlying logic.
In the upcoming installment, I’m going to define another method within the “AbstractModel” class that will be responsible for deleting a specified record from its associated database table. Therefore, now that you know what to expect from the next part, you can’t miss it!
DISCLAIMER: The content provided in this article is not warranted or guaranteed by Developer Shed, Inc. The content provided is intended for entertainment and/or educational purposes in order to introduce to the reader key ideas, concepts, and/or product reviews. As such it is incumbent upon the reader to employ real-world tactics for security and implementation of best practices. We are not liable for any negative consequences that may result from implementing any information covered in our articles or tutorials. If this is a hardware review, it is not recommended to open and/or modify your hardware.