Advertisement

Codeigniter

Codeigniter CRUD: Day 3 Read Operation

Codeigniter | Crud | Mvc

Codeigniter CRUD Day 3

Advertisement

This entry is part 3 of 6 in the series CodeIgniter CRUD

Codeigniter CRUD: Day 3 Read Operation: In Day 2 Create Operation we created view & controller for create operation to work. which is responsible for showing form for new post entry and saving it to database via post model. Now we have our create operation ready let’s move on to Read Operation of Codeigniter CRUD. So that we can list already created posts.

Controller code for Codeigniter CRUD’s Read Operation

Create a method in post controller named index and add following code in it.

Controller part for Codeigniter CRUD Read operation is fairly simple. We just have to call model method getAll(). It will return array containing all posts available in database. We just stored in a variable and pass it to index view inside views/post directory. Remember we pass whole $data variable which is an array again. so every key of that array will become a variable in view. so we already created a $posts variable for view.

Index View code for Codeigniter CRUD’s Read Operation

Create a new file inside views/post and name it index.php. Add following code in it.

First we added few stylesheet. Basically that I do after setting HTML. After that we have a table for posts listing. inside tbody element I ran a loop of foreach to fetch all posts one by one and output in HTML. As you can see we have a $post object and we can access every field of that using stdobject method. Variable $i is just for setting even class for alternate row color in table.

Now open browser and navigate to  http://localhost:8888/ci/index.php/post  and you will see similar to below screenshot.

Codeigniter CRUD Read Operation

As you can see we also add link to create, update & delete operation. We also want to redirect to index method when new post is added instead on create method itself. Let’s fix that.

Open post controller and modify create method function with highlighted line of code shows. Full Controller code is as below:

So we have our Read operation of Codeigniter CRUD working perfectly. So let’s move forward to Update operation for Codeigniter CRUD.

 

Download Source Code Files

Please like our Facebook Fan page for instant updates on Tutorials.

Series Navigation<< Codeigniter CRUD: Day 2 Create OperationCodeigniter CRUD: Day 4 Update Operation >>

Bookmark Link using: bookmark at folkd