Since my plan consists basically of demonstrating how to build a basic PHP application, capable of paging a few database rows, I’m going to use the same sample “users” MySQL table that was created in the previous article. As you’ll recall, the table was populated with data about some fictional users. Its structure looked like this:
Now that you’re familiar with the above MySQL table, it’s time to build a model class that permits us to access its rows in a painless fashion. So take a look at the following “User” model class, which accomplishes this task. Here it is: class Users extends Model{ function Users(){ // call the Model constructor parent::Model(); // load database class and connect to MySQL $this->load->database(); } function getAllUsers(){ $query=$this->db->get('users'); if($query->num_rows()>0){ // return result set as an associative array return $query->result_array(); } } function getUsersWhere($field,$param){ $this->db->where($field,$param); $query=$this->db->get('users'); // return result set as an associative array return $query->result_array(); } // get 5 rows at a time function getUsers($row){ $query=$this->db->get('users',5,$row); if($query->num_rows()>0){ // return result set as an associative array return $query->result_array(); } } // get total number of users function getNumUsers(){ return $this->db->count_all('users'); } } If you read the preceding tutorial of the series, it’s possible that you find the above model class pretty familiar. As you can see, it presents a group of methods that can be used for fetching both single and multiple rows from the pertinent “users” MySQL table, as well for counting the number of records contained within a given result set. Also, it’s worthwhile to clarify again that this model implements all of its methods thanks to the functionality of the database class included with Code Igniter, which is loaded by the corresponding constructor. However, you should pay close attention to the signature of a brand new method, called “getUsers().” It permits the program to fetch five rows at time. I’m going to take advantage of its functionality to build a simple, yet effective, paging system. Now that you hopefully grasped how the previous model class does its thing, please save it to the system/application/models/ folder and jump forward to see how to define the other building block of this MySQL-driven application. In this case, I’m talking about the corresponding controller class, which not only will be capable of embedding database contents into a view file, but will also implement the aforementioned paging mechanism. To learn how this controller class will be constructed, please click on the link that appears below and keep reading.
blog comments powered by Disqus |
|
|
|
|
|
|
|