Sunday 24 November 2013

Simple PHP Code in Codeigniter

This section will show you how to create the admin page for our blog, with pages to create and edit blog posts. By the end of this part you should have a functioning admin page (that requires login!) displaying a list of posts from the database, with links to view, edit, or delete the post.

We’re gonna want to add the methods to insert, update, and delete posts. With CodeIgniter manipulating database data is simplified.

Go back to the Posts model located at :

/application/models/posts.php

Copy the extra methods to our Post model from the code below :

  1. <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
  2. class Posts extends CI_Model
  3. {
  4.        
  5.         function __construct()
  6.         {
  7.                 parent::__construct();
  8.         }
  9.         // If $postId is NULL, gets all posts, otherwise get single post from db
  10.         // returns $post[]
  11.         public function get_posts($postId)
  12.         {
  13.                 $post=array();
  14.                 if ($postId !== null){         
  15.                         $query = $this->db->get_where('posts', array('id' =>$postId));
  16.                         if ($query->num_rows() == 1) { 
  17.                                 foreach($query->result() as $row){
  18.                                 $post['id'] = $row->id;
  19.                                 $post['title'] = $row->title;
  20.                                 $post['summary'] = $row->summary;
  21.                                 $post['content'] = $row->content;
  22.                                 }
  23.                                 return $post;
  24.                         }      
  25.                 } else {
  26.                         $query = $this->db->get('posts');
  27.                         if ($query->num_rows() !== 0 ){
  28.                                 foreach($query->result() as $row){
  29.                                 $post['id'][] = $row->id;
  30.                                 $post['title'][] = $row->title;
  31.                                 $post['summary'][] = $row->summary;
  32.                                 $post['content'][] = $row->content;
  33.                                 }
  34.                                 return $post;
  35.                         }
  36.                        
  37.                 }              
  38.         }
  39.         function insert_post($data){
  40.                 $this->db->insert('posts', $data);
  41.                 return;
  42.         }
  43.         function update_post($postId, $data){
  44.                 $id = $postId;         
  45.                 $this->db->where('id',$id);
  46.                 $this->db->update('posts', $data);
  47.                 return;
  48.         }
  49.         function delete_post($postId){
  50.                 $id = $postId;         
  51.                 $this->db->delete('posts',array('id' => $id));
  52.                 return;
  53.         }
  54. }

Views

Once again we’re going to need to create a few simple view files for our admin index page, a new html head wrapper file that will have a ‘Logout’ link instead of an ‘Admin’ link, and forms for creating/editing posts.

Create admin_html_head.php at this location :

/application/views/template/admin_html_head.php

Copy the code below :
  1. <!DOCTYPE html>
  2.         <head>
  3.                 <link rel="stylesheet" type="text/css" href="<?php echobase_url('style.css');?>">
  4.         </head>
  5.         <body>
  6.                 <h1><?php echo anchor('','My Blog'); ?></h1>
  7.                 <div id="loginDiv"><?php echo anchor('admin/logout','Logout');?></div>
  8.                 <hr/>

Create index.php at this location :

/application/views/admin/index.php

Copy the code below :
  1. <?php
  2.         echo '<p>Welcome To The Admin Page '.$username.'! All posts available for edit or deletion is listed below.</p><br/>';
  3.         echo anchor('admin/create','Create New Post');
  4.         $count = count($post['id']);
  5.         for ($i=0;$i<$count;$i++)
  6.         {
  7.                 echo '<div class="postDiv">';
  8.                 echo '<h4>'.$post['title'][$i];
  9.                 echo anchor('blog/view/'.$post['id'][$i],' [view]');
  10.                 echo anchor('admin/edit/'.$post['id'][$i],' [edit]');
  11.                 echo anchor('admin/delete/'.$post['id'][$i],' [delete]</h4>');
  12.                 echo '<p>'.$post['summary'][$i].'</p>';
  13.                 echo '</div>';
  14.         }
  15. ?>

reate create.php at this location :

/application/views/admin/create.php

Copy the code below :
  1. <?php
  2.         echo validation_errors();
  3. ?>
  4.         <h4>Create A New Post Below</h4>
  5.         <form action="" method="post" >
  6.         <p>Title:</p>
  7.         <input type="text" name="title" size="50"/><br/>       
  8.         <p>Summary:</p>
  9.         <textarea name="summary" rows="2" cols="50"></textarea><br/>
  10.         <p>Post Content:</p>
  11.         <textarea name="content" rows="6" cols="50"></textarea><br/>
  12.         <input type="submit" value="Save" />
  13. <?php
  14.         echo anchor('admin','Cancel');
  15. ?>
  16.         </form>

Create edit.php at this location :

/application/views/admin/edit.php

Copy the code below :
  1. <?php
  2.         echo validation_errors();
  3. ?>
  4.         <h4>Edit "<?php echo $post['title']; ?>" Below</h4>
  5.         <form action="" method="post" >
  6.                 <p>Title:</p>
  7.                 <input type="text" name="title" size="50" value="<?php echo$post['title']; ?>"/><br/> 
  8.                 <p>Summary:</p>
  9.                 <textarea name="summary" rows="2" cols="50"><?php echo$post['summary']; ?>
  10.                 </textarea><br/>
  11.                 <p>Post Content:</p>
  12.                 <textarea name="content" rows="6" cols="50"><?php echo$post['content']; ?>
  13.                 </textarea><br/>
  14.                 <input type="submit" value="Save" />
  15. <?php
  16.         echo anchor('admin','Cancel');
  17. ?>
  18.         </form>

Controller

Our final controller will tie all of our admin page logic together, calling the method functions and loading the view files we just created as requested.

Create admin.php at this location :

/application/controllers/admin.php

Copy the code below :
  1. <?php if (!defined('BASEPATH')) exit('No direct script access allowed');
  2. class Admin extends CI_Controller
  3. {
  4.         function __construct()
  5.         {
  6.                 parent::__construct();
  7.                 $this->load->helper(array('form','url'));
  8.                 $this->load->library(array('tank_auth','form_validation'));
  9.                 $this->load->model('posts');
  10.         }
  11.         function index() {
  12.                 if (!$this->tank_auth->is_logged_in()) {
  13.                         redirect('/auth/login');
  14.                 } else {
  15.                         $data['post'] = $this->posts->get_posts(null);
  16.                         $data['userId'] = $this->tank_auth->get_user_id();
  17.                         $data['username'] = $this->tank_auth->get_username();
  18.        
  19.                         $this->load->view('template/admin_html_head', $data);
  20.                         $this->load->view('admin/index', $data);
  21.                         $this->load->view('template/html_tail', $data);
  22.                 }
  23.         }
  24.         function create(){
  25.                 $data['userId'] = $this->tank_auth->get_user_id();
  26.                 $data['username'] = $this->tank_auth->get_username();
  27.                 $this->form_validation->set_rules('title','title','required');
  28.                 $this->form_validation->set_rules('summary','summary','required');
  29.                 $this->form_validation->set_rules('content','content','required');
  30.                 if($this->form_validation->run()==FALSE)
  31.                 {
  32.                         $this->load->view('template/admin_html_head',$data);
  33.                         $this->load->view('admin/create',$data);
  34.                         $this->load->view('template/html_tail',$data);
  35.                 } else {
  36.                         $data = $_POST;
  37.                         $this->posts->insert_post($data);
  38.                         redirect('admin');
  39.                 }
  40.         }
  41.         function edit($postId){
  42.                 $data['userId'] = $this->tank_auth->get_user_id();
  43.                 $data['username'] = $this->tank_auth->get_username();
  44.                 $data['post'] = $this->posts->get_posts($postId);
  45.                 $this->form_validation->set_rules('title','title','required');
  46.                 $this->form_validation->set_rules('summary','summary','required');
  47.                 $this->form_validation->set_rules('content','content','required');
  48.                 if($this->form_validation->run()==FALSE)
  49.                 {
  50.                         $this->load->view('template/admin_html_head',$data);
  51.                         $this->load->view('admin/edit',$data);
  52.                         $this->load->view('template/html_tail',$data);
  53.                 } else {
  54.                         $data = $_POST;
  55.                         $this->posts->update_post($postId, $data);
  56.                         redirect('admin');
  57.                 }
  58.         }
  59.         function delete($postId){
  60.                 $this->posts->delete_post($postId);
  61.                 redirect('admin');
  62.         }
  63.         function logout(){
  64.                 redirect ('/auth/logout');
  65.         }
  66. }

Change Tank Auth’s Behavior

Since we’re only using the Tank Auth authentication for our admin page, instead of our entire application, we need to tweak it’s functionality a bit.

Currently logging in to the admin section will take us directly back to the main blog index (although the user is successfully logged in), and then clicking the ‘Admin’ link one more time is required to gain access to the Admin index page. We’re going to fix this by redirecting back to our ‘Admin’ controller index immediately after a successful login.

Open auth.php located here:

/application/controllers/auth.php

Find the line that says (around line 71) :
  1. // success
  2. redirect('');

Replace with the code below and save :
  1. // success
  2. redirect('admin');
Also, logging out would currently bring us immediately back to the login form, instead of back to the blog index as we would want. We’re going to fix this by inserting a new line telling the controller to redirect back to admin index right after logging a user out.

Go back to auth.php, find method ‘logout’ (around line 106) :
  1. function logout()
  2.         {
  3.                 $this->tank_auth->logout();
  4.                 $this->_show_message($this->lang->line('auth_message_logged_out'));
  5.                
  6.         }

Replace with the code below and save :

  1. function logout()
  2.         {
  3.                 $this->tank_auth->logout();
  4.                 redirect('');
  5.                 //$this->_show_message($this->lang->line('auth_message_logged_out'));
  6.                
  7.         }

Before our blog is complete we’re going to want to change to tell the Auth controller to wrap it’s loaded views around our HTML wrappers just like our other controllers.

Find these lines one at a time:

$this->load->view(‘auth/login_form’, $data);
$this->load->view(‘auth/register_form’, $data);
$this->load->view(‘auth/forgot_password_form’, $data);
$this->load->view(‘auth/reset_password_form’, $data);
$this->load->view(‘auth/change_password_form’, $data);
$this->load->view(‘auth/unregister_form’, $data);

For EACH line you must insert the following lines :

Insert this BEFORE the line:
$this->load->view(‘template/html_head’, $data);

Insert this AFTER the line:
$this->load->view(‘template/html_tail’, $data);

Using the same HTML wrappers over and over, we can quickly create many lovely views for the Tank Auth forms easily.
Registration form with the HTML wrappers around it.
Login form with the HTML wrappers around it.

Conclusion

You should now have a simple blog that displays posts as well as having a separate admin section to serve as a very simple “content management system” CMS.

Index for our Admin controller.


blog-admin-create
blog-admin-edit
 hope this helped you!

I hope all goes well! Look forward to seeing more post from Anjaneya Vadivel  in the future.

Please comment below!

1 comment:

  1. Nice Tutorial...i got useful information from this tutorial,here is a way to findsimple registration form using codeigniter

    ReplyDelete

Simple CRUD in Laravel Framework

Creating, reading, updating, and deleting resources is used in pretty much every application. Laravel helps make the process easy using re...