Completing a Model for the CodeIgniter PHP Framework - Performing generic SQL queries
(Page 2 of 4 )
As I stated in the introduction, the generic model still lacks some features that need to be implemented quickly, including the ability to perform any type of SQL query, as well as clean up the model’s status. Thus, to address these specific issues, I’m going to add to it a simple method that will allow it to execute different queries against the associated database table.
That being explained, here’s the complete signature of the generic model class, incorporating the extra methods I just mentioned. Have a look at it:
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
* @return result set/Boolean TRUE on success - Boolean FALSE on failure
* @access public
*/
public function query($query)
{
if (is_string($query))
{
if (FALSE === ($query = $this->db->query($query)))
{
$this->errors[] = 'Error performing query.';
}
return $query;
}
}
}
As shown above, apart from the methods that are responsible for performing CRUD database operations and validating incoming data, the model class now incorporates a new one, called “query().” As I explained previously, this method is conceived to execute any type of SQL query; it’ll return a value of FALSE if the query fails its execution, or a result set if it is successful.
Undoubtedly, the logic that drives the “query()” method is extremely simple to grasp, so it’s time to continue adding more functionality to the “AbstractModel” class. In accordance with the concepts deployed in the introduction, I'm going to code a few additional methods that will be charged with resetting the state of the model, as well as with building the corresponding error messages that will be displayed to users when it fails to perform a given task.
This topic will be covered in depth in the next section, so click on the link that appears below and read the next few lines.