Inserting Database Records with a CodeIgniter PHP Framework Model - Coding a method for inserting database records
(Page 3 of 4 )
Definitely, one of the principal features that any decent model class must have is the capability to insert and update rows in a specified database table. With that in mind, in the next few lines I’m going to add another method to the “AbstractModel” class, which will be tasked with performing insertions and updates against its associated table.
Here’s how this brand new method looks:
/** Saves model data into associated table (validation rules are applied to input data)
*
*
* @author Alejandro Gervasio
* @return integer on success - Boolean FALSE on failure
As you can see, the logic implemented by the previous “save()” method is fairly easy to follow. In this case, the method will insert a new record into the specified database only if the $this->id property has been previously set. Otherwise, it’ll perform an update operation using the aforementioned property.
Finally, it’s valid to mention that if no data is supplied for inserting or updating a record in the database, then the corresponding error message will be stored in the $this->errors array and the method will return a FALSE value. Not too difficult to grasp, right?
So far, so good. Now that you hopefully understood how the previous “save()” method does its thing, it’s time to see how the generic model looks after incorporating this new method. So, in the last section of this tutorial I’m going to list for you the complete source code of the model, so can see more clearly how it is now structured.
Please click on the link below and read the following segment.