Showing posts with label CodeIgniter. Show all posts
Showing posts with label CodeIgniter. Show all posts

Tuesday, 3 November 2015

Common join function in codeigniter for listing

Here's a very simple example to get you started
Construct $joins as array:

$joins = array(
    array(
        'table' => 'table2',
        'condition' => 'table2.id = table1.id',
        'jointype' => 'LEFT'
    ),
);
Example function handling joins as an array:
 public function get_joins($table, $columns, $joins)
{
    $this->db->select($columns)->from($table);
    if (is_array($joins) && count($joins) > 0)
    {
        foreach($joins as $k => $v)
        {
            $this->db->join($v['table'], $v['condition'], $v['jointype']);
        }
    }
    return $this->db->get()->result_array();
}

Common select query in Codeigniter (Single Function)

This is the codeigniter function for common select query that you need to place in model. and call it from controller. 

function db_select($select, $from, $where = array(), $group = array(), $order = '', $having = '', $limit =array(), $result_way = 'all', $echo = 0) {
        $result = array();
        $this->db->select($select);
        $this->db->from($from);
        if (!empty($where)) {            $this->db->where($where);        }
        if (!empty($group)) {            $this->db->group_by($group);        }
        if ($order != '') {            $this->db->order_by($order);        }
        if (isset($limit[0])) {                       $this->db->limit($limit[0]);//example $limit[0] = "0,10" where  0 is for offset and 10 for limit
        }
        $temp = $this->db->get();
        switch ($result_way) {
            case 'row':
                $result = $temp->row();
                break;
            case 'row_array':
                $result = $temp->row_array();
                break;
            case 'count':
                $result = $temp->num_rows();
                break;
            default:
                $result = $temp->result_array();
                break;
        }
        if ($echo == 1) {
            echo $this->db->last_query();
            exit;
        }        return $result;    }
suppose your model name is say “basic_model” than you need to call this function in controller like..

$t = $this->basic->db_select('user_id', 'tbl_user', $wh=array("user_id"=>1), array("user_id"), 'user_id desc', '', '', 'row_array');

Parameter understanding :
$select           : string of database table column in comma separated or * for all column
$from             : string of database table name
$where          : An associative array in which array key should be table column and array value would be table column value
$group          : an array of database column e.g array(“user_id”) so it gives output as group by user_id
$order           : string of database column with ASC or DESC parameter e.g ‘user_id DESC’
$having        : string of database column with condition say sum(‘coin’) > 0
$limit            : an array of limit string e.g array(“10,0″) so this gives output as limit 0,10
$result_way : string for output way
$echo           : 0 or 1 . if you want the query string from codeigniter than set this value as 1
By changing the query guide functionality you can use this function for other framework or in cms.

Sunday, 24 November 2013

Codeigniter MVC class and functions template

Hi this is Anjaneya Vadivel, Every time I make a website I usually try to plan my classes out ahead of time in a regular text file, this small step will reduce the amount of time spent figuring out how to design my application considerably. I find this especially useful when working with CodeIgniter. I can even create all the files ahead of time, (usually I use the touch command in terminal to do it quickly).

This is how my template might look before being filled out :

Example Class Template

MODEL: (classes with functions to GET/INSERT/UPDATE/DELETE from the database, called from controller classes)

model_class.php
[some functions listed here]

CONTROLLER: (functions to handle user requests : call model functions and load up views)

class_a.php
[some functions listed here]

class_b.php
[some functions listed here]

VIEW: (PHP files that contain the necessary html to see the page, loaded from controller classes)

template/html_head.php
template/html_tail.php

Example Blog Class Template

Once again this is not a completed template below as the functions would usually be filled in with as much information as I can plan before starting the actual application. This means thinking of all parameter names, and the insides of the functions before starting.

MODEL:

posts_model.php

get_posts()
get_post_by_id()
get_tags_by_post_id()
insert_post()
update_post_by_id()
delete_post_by_id()
etc…

CONTROLLER:

posts.php

index()
etc

pages.php

index($page)
etc…

VIEW:

template/html_head.php
template/html_tail.php
post/single_view.php
post/multi_view.php
page/contact_us
page/home
etc…

Why plan?

If you don’t already create a template to help organize your thoughts when programming, you should try it! It’s the easiest way to see the amount of work that needs to be done, divide work among multiple people easily, and help make MVC programming a little more intuitive.

How much planning do you do before starting your application?

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>

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...