Fetching Database Rows with a Model for the CodeIgniter PHP Framework - Implementing the fetch() method
(Page 3 of 4 )
Since the method of the model class that I’m about to code will be responsible for fetching rows from the associated database table, I decided to call it simply “fetch(),” but it’s usual to name it “get(),” “find(),” and so forth. Basically, this method will perform SELECT statements in accordance with certain query modifiers, which will be passed in to it as a succession of arguments.
That being explained, here’s the implementation of the aforementioned “fetch()” method. Take a look at it:
/**
* Returns a result set with specified fields according to given conditions.
*
* @author Alejandro Gervasio
* @return query result on success - Boolean FALSE on failure
$this->errors[] ='No rows were returned by the query.';
return FALSE;
}
As I explained previously, this method will return a result set from the specified database table in accordance with different arguments, which has been assigned a default value that varies for each particular case. Also, it’s worthwhile to note that the workhorse of this method is CodeIgniter’s Active Record class, so again I recommend that you read the pertinent user guide if you’re not familiar with it.
Finally, it’s valid to mention that if the “$this->id” property of the model has been set in the proper controller, then it’ll return the row that matches that ID. Otherwise, it’ll return a multi-row data set if the group of conditions passed in as parameters produces a valid result.
Undeniably, the implementation of the “fetch()” method is very intuitive, meaning that you shouldn’t have major trouble grasping its logic. However, as with everything in life, it can be improved or even completely overridden, but that will be left as homework for you.
At this point, I've already shown you the signature of one of the core methods of the model class. Therefore, it’s time to go one step forward and list the complete source code of the class in question, this time including the “fetch()” method that you just saw a few moments ago.
This will be accomplished in the final section of this article, so click on the link below and read the following segment.