Showing posts with label Codeigniter. Show all posts
Showing posts with label Codeigniter. Show all posts

Tuesday, 23 October 2018

10 Quick CodeIgniter Tips

Simplify your framework-building experience with 10 CodeIgniter Tips


Introduction
Whether you are a newbie to CodeIgniter or a CodeIgniter Pro, there’s always more you can learn to make the process easier. I have compiled 10 quick CodeIgniter tips to make your experience with CodeIgniter smoother.
Here are the first 5 CodeIgniter tips:
1. Follow the CI default structure.
CodeIgniter comes with the default MVC pattern structure. Follow this basic structure. It is fairly common for most frameworks and for CI as well. When using the MVC structure use Controllers for logins, Models for database interaction and Views for HTML.
2. Use CI form validations.
Codeigniter provides built-in form validation features, which are very easy to use. I would recommend using CI form validations. It provides you the facility to set the rules, run validations and display messages.
To set the rules you can use the following syntax:
$this->form_validation->set_rules();
Example:
$this->form_validation->set_rules('email', 'Email', 'required');
You can also set cascading rules like this:
$this->form_validation->set_rules('email', 'Email', 'required|max_length[12]|is_unique[users.email]');
3. Sanitize your inputs.
Always sanitize your inputs before submitting the data to the database. This is very important for the application to prevent SQL (Structured Query Language) injections and to store only valid data into the database. Be sure that you always clean the inputs.
In CodeIgniter you can use the following method to clean your inputs:
$employees = $this->security->xss_clean($employees);
By setting a global (config) setting in CodeIgniter, you can run this filter automatically each time there is a post requested or cookie data fetched.
$config['global_xss_filtering'] = TRUE;
Note: Sanitize_filename() is also used to cross-check the file inputs from the user.
4. Protect your site from Cross-Site Request Forgery (CSRF).
To protect the site from CSRF attacks always enable the CodeIgniter settings for CSRF protection. To enable it, open your config file and look for the code written below:
$config['csrf_protection'] = TRUE;
5. Try to use CI-preferred styling and commenting.
CodeIgniter provides an excellent set of styles and commenting to format your code well. It works best if everybody uses the same recommendation for the framework. That way other developers can understand the code you are writing.
Here are the next 5 CodeIgniter tips:
6. Use caching techniques like Query Caching.
CI provides the database class that is used to cache your queries and reduce the database load. CodeIgniter loads this class automatically. You don’t have to do it manually if caching is enabled. You can enable the cache inside the database.php file, under config directory.
$db['default'] = array(
'dsn' => '',
'hostname' => 'localhost',
'username' => '',
'password' => '',
'database' => '',
'dbdriver' => 'mysqli',
'dbprefix' => '',
'pconnect' => FALSE,
'db_debug' => (ENVIRONMENT !== 'production'),
'cache_on' => FALSE,
'cachedir' => '',
'char_set' => 'utf8',
'dbcollat' => 'utf8_general_ci',
'swap_pre' => '',
'encrypt' => FALSE,
'compress' => FALSE,
'stricton' => FALSE,
'failover' => array(),
'save_queries' => TRUE
);
Note: You can try different caching techniques as well, like memcached and CI3 also integrated with RedIs.
7. Remove index.php from the URLs.
Always remove the index.php URLs to SEO-friendly URLs. Change your .htaccess code to make it work?
For example:
To change config file:
$config['index_page'] = "index.php"
to
$config['index_page'] = ""
To change in your .htaccess file:
RewriteEngine On
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L]
8. Don’t use PHP code, use an alternative in CodeIgniter.
I recommend that you not write your own PHP code. Find the CI alternative for everything you want to implement.
9. Create helpers for your most-often-used functions.
For the most commonly used functions always create the helpers. Helpers are just a set of functions for any specific functionality or category. To use the helpers, you have to load them. They do not load by default. This is how to load a helper:
$this->load->helper('helper_name');
10. The Config directory should have all the configuration information.
Keep all configuration files under the config directory. If they are outside the directory you may not be able to find them as easily. In the long run, putting the files into the directory will help when you’re working on big projects.
Note: Always load what is required for your application. Don’t load anything that is not needed. For this, you can use the constructor of your controller, if you only want to load part of the functionality.
There are many other ways to simplify your work when building with CodeIgniter. I hope these 10 CodeIgniter tips will make your experience with CodeIgniter better. 

Wednesday, 10 October 2018

Default Custom Model in CodeIgniter

Assalamualaikum dan salam sejahtera..

Untuk memudahkan pembangunan sistem menggunakan CodeIgniter, penggunaan default Model amatlah digalakkan kerana ianya lebih tersusun selagi mana struktur data tidak terlalu kompleks.

Default Model ini juga boleh diubahsuai mengikut keperluan semasa. Default model ini perlu dimasukkan dalam satu page yang dikenali sebagai MyModel.php.

Contoh Code Dalam Default Model:

1. Untuk mendapatkan satu field

Controller:
$data = $this->MyModel->get_one_field('FirstName','NRIC = '700101017254','User');

Model:
function get_one_field($col,$where,$table)
{
   $this->db->select($col);
   $this->db->where($where);
   $query = $this->db->get($table);
   return $query->row_array();
}

2. Untuk mendapatkan set data

Controller:
$data = $this->MyModel->get_data('User');

Model:
function get_data($table)
{
   $this->db->select('*');
   $this->db->from($table);
   $query = $this->db->get();
   return $query->result_array();
}

3. Untuk mendapatkan satu set data

Controller:
$data = $this->MyModel->get_info('User', array('NRIC'=>'700101017254', 'Active'=>'Y'));

Model:
function get_info($table,$where=0)
{
    $this->db->select('*');
    $this->db->from($table);
    if($where != 0)
    {
      foreach($where as $key=>$val){
         $this->db->where($key, $val);
      } 
    }
    $query = $this->db->get();
    return $query->row_array();
}

4. Untuk membuat pengiraan data

Controller:
$data = $this->MyModel->get_count('User', array('Active'=>'Y','Gender'=>'F'));

Model:
function get_count($table,$where)
{  
    $this->db->from($table);
    $this->db->where($where);
    return $this->db->count_all_results();
}

5. Untuk mendapatkan jumlah

Controller:
$data = $this->MyModel->get_sum('User', 'Fee', array('Active'=>'Y','Gender'=>'F'));

Model:
function get_sum($table,$field,$where)
{
    $this->db->select_sum($field);
    $this->db->where($where);
    $query = $this->db->get($table);  
    return $query->row_array();     
}

6. Untuk membuat list dropdown

Controller:
$data = $this->MyModel->get_select_list('Title',array('key'=>'id','val'=>'description','orderby'=>'id'),1, array('Active'=>'Y'));

Model:
function get_select_list($table,$cols=array('key' => 'id','val' => 'name', 'orderby' => 'x'),$with_select=1, $where='x')
{
    extract($cols);
    if($orderby=='x'){
       $this->db->order_by($val);
    }
    if($where!='x')
       $this->db->where($where);
       $query = $this->db->get($table);
       $arr = $query->result_array();
    if ($with_select) $data[''] = '-- Select --';
       foreach ($arr as $k => $v){
          extract($v);
          $data[$$key] = $$val;
       }
    return $data;
}

7. Join Table

Controller:
$data = $this->MyModel->get_valueJoin('Title','Title.id = User.title',array('Gender'=>'M'),'FirstName', 'User');

Model:
function get_valueJoin($join,$join1,$where,$field,$table)
{
    $this->db->join($join,$join1);
    $this->db->where($where);
    $this->db->order_by($field, "asc");
    $query = $this->db->get($table);
    return $query->result_array();
}

8. Insert Data

Controller:
//post data
$data['user']['title'] = $this->input->post('title');
$data['user']['name'] = $this->input->post('name');
$data['user']['dob'] = date('Y-m-d',strtotime($this->input->post('dob')));
$data['user']['gender'] = $this->input->post('gender');
$data['user']['race'] = $this->input->post('race');

$data = $this->MyModel->insert_data('User',$data['user']);

Model:
function insert_data($table,$data)
{
    if ($this->db->insert($table, $data)) {
       return $this->db->insert_id();
    }
    else return false;
}

9. Update Data

Controller:
$user = $this->MyModel->get_info('User', array('NRIC'=>'700101017254', 'Active'=>'Y'));

//post data
$data['user']['title'] = $this->input->post('title');
$data['user']['name'] = $this->input->post('name');
$data['user']['dob'] = date('Y-m-d',strtotime($this->input->post('dob')));
$data['user']['gender'] = $this->input->post('gender');
$data['user']['race'] = $this->input->post('race');

$data = $this->MyModel->update_data('User',$user['id'],$data['user']);

Model:
function update_data($table,$key,$data)
{
    $this->db->where($key);
    $this->db->update($table, $data);
}

10. Delete data

Controller:
$data = $this->MyModel->delete_data('User',array('NRIC'=>'700101017254'));

Model:
function delete_data($table,$where=0)
{
   if($where != 0)
   {
      foreach($where as $key=>$val){
         $this->db->where($key, $val);
      } 
   }
   $this->db->delete($table);
}


*******************************
Disediakan Oleh :
Haslina Shamsudin
PPTMK
Unit Pengaturcaraan

Wednesday, 26 October 2016

MENGUBAH JENIS GRAF MENGGUNAKAN FUSIONCHARTS DI DALAM SESEBUAH APLIKASI SISTEM

GRAF FUSSION CHART

Pada umumnya untuk mendapatkan sesebuah laporan, adalah lebih mudah difahami jika disertakan dengan sebuah graf yang menarik. Rekabentuk graf / kategori graf yang dipilih mestilah bersesuaian dengan laporan yang ingin dipaparkan agar mudah difahami oleh pengguna.

Berikut adalah satu coding jenis graf yang telah dipilih.



Coding : 
         $graph_swfFile      = base_url().'assets/fscharts/MSColumn3D.swf'; 
         $graph_width        = 850 ;
         $graph_height       = 450 ;




PAPARAN PADA SISTEM



Download Fussionchart ke dalam server sistem development.



Maklumat jenis graf / filename boleh dirujuk melalui  url : http://www.fusioncharts.com/dev/




Disediakan oleh : Mariatulkibtiah binti Arshad
Rujukan : Sistem QAP (Penjagaan Kesihatan Premier)

Tuesday, 27 October 2015

MEMASUKKAN DATA KE DALAM 2 TABLE MENGGUNAKAN CODEIGNITER

Memasukkan Data Ke Dalam 2 Table menggunakan CodeIgniter
1-Table User
  • user_id(int)
  • user_email(varchar(64))
  • user_name(varchar(64))
  • user_pass(varchar(64))
2-Table Profiles
  • prof_id(int)
  • user_id(int)
  • first_name(varchar(64))
  • last_name(varchar(64))
Controller : Umpukkan 2 Variable dalam 2 Jenis Array berbeza ($data1 & $data2)
function add_account() {
    $this->load->model('m_signup');
    // get form variable
    $first_name = $this->input->post('first_name');
    $last_name = $this->input->post('last_name');
    $user_email = $this->input->post('user_email');
    $user_name = $this->input->post('user_name');
    $user_pass = $this->input->post('user_pass');


    $data1 = array($user_name, $user_email, $user_pass);
    $data2 = array($first_name, $last_name);

    $this->m_signup->add_account($data1, $data2);

    redirect('login');
}
Models  
function add_account($data1, $data2) {
    $this->db->trans_start();

    $sql1 = "INSERT INTO users(user_name, user_email, user_pass) 
            VALUES (?, ?, ?)";

    $this->db->query($sql1, $data1); 
    $id_user = $this->db->insert_id(); 

    $sql2 = "INSERT INTO profiles(user_id, first_name, last_name) 
            VALUES ($id_user, ?, ?)"; 
    $this->db->query($sql2, $data2);

   $this->db->trans_complete(); 

  return $this->db->insert_id(); 

}
Abd Rahman Bin Sirat

Rujukan : http://stackoverflow.com/questions/21076413/insert-array-data-into-two-table-using-codeigniter
   

Monday, 26 October 2015

PENGGUNAAN PLACEHOLDER

PENGGUNAAN PLACEHOLDER





CODING

<?php echo tbs_horizontal_input(array(
                 'name'=>'tahun',
                 'id'=>'tahun',
                 'value'=>  set_value('tahun', $data['tahun']),
                  'placeholder'=>'Contoh: 2015',
                 'class'=>'input-small',
             ), array(
                 'label'=>'Tahun',
             ), false);
              ?>



Disediakan oleh : Mariatulkibtiah binti Arshad
sumber : Sistem eMINDA

Friday, 23 October 2015

CHECK EXISTING MYKAD IN DATABASE

1. Create MYKAD field & Javascript function in views. Example : views/carian/tambah_rekod.php

<div class="">
    <div class="span10 offset1">
        <div class="widget-box" >
            <div class="widget-title">
                <span class="icon">
                    <i class="icon-th-large"></i>
                </span>
                <h5>Daftar Pengguna</h5>
            </div>
            <div class="widget-content" >
        
        
        <?php echo tbs_horizontal_form_open('carian/tambah_rekod', array('id'=>'tambah_rekod'));?>

        <div class="alert alert-fail">
            <span id="msgbox"></span>
        </div> 
        <div style="margin-left: 10px;  ">

        <?php echo tbs_horizontal_input(array(      //validation using jquery -> assets/validation/register.js
            'name'=>'mykad', 
            'id'=>'mykad',
            'value'=>set_value('mykad', $mykad),
            'class'=>'input-large',
            'maxlength'=>'12',
    //        'readonly' => 'readonly',
        ), array(
            'label'=>'No. MyKad', 
            
        ), true); 
        ?>
                
        <?php echo tbs_horizontal_input(array(
            'name'=>'nama',
            'id'=>'nama',
            'value'=>  set_value('nama',  $nama),
            'class'=>'input-xxlarge',
            //'readonly' => 'readonly',
        ), array(
            'label'=>'Nama',
        ), true); ?>
     
     
         <?php echo tbs_horizontal_dropdown('jantina',$jantina_u,
        $jantina, array(
            'id'=>'jantina',
            //'value'=>  set_value('jantina',  $jantina),
            'class'=>'input-medium',
            //'disabled' => 'disabled',
        ), array(
            'label'=>'Jantina',
        ), true); ?>     
            
        <?php echo tbs_horizontal_password(array(
            'name'=>'katalaluan',
            'id'=>'katalaluan',
            'value'=>set_value('katalaluan', $katalaluan),
            'class'=>'input-medium',
            //'readonly' => 'readonly',
        ), array(
            'label'=>'Kata Laluan',
        ), true); ?>            
            
         <?php echo tbs_horizontal_password(array(
            'name'=>'re_katalaluan',
            'id'=>'re_katalaluan',
            'value'=>set_value('re_katalaluan', $re_katalaluan),
            'class'=>'input-medium',
            //'readonly' => 'readonly',
        ), array(
            'label'=>'Pengesahan Kata Laluan',
        ), true); ?>             
         
         <?php echo tbs_horizontal_input(array(
            'name'=>'emel',
            'id'=>'emel',
            'value'=>  set_value('emel', $emel),
            'class'=>'input-xlarge',
            //'readonly' => 'readonly',
        ), array(
            'label'=>'Emel',
        ), true); ?>
       
           <?php echo tbs_horizontal_dropdown('skim', $skim_u,
        $skim, array(
            'id'=>'skim',
            'class'=>'input-xlarge',
            //'disabled' => 'disabled',
        ), array(
            'label'=>'Jawatan',
        ), true)?>         
            
            
          <?php echo tbs_horizontal_input(array(
            'name'=>'gred',
            'id'=>'gred',
            'value'=>  set_value('gred',  $gred),
            'class'=>'input-small',
            'maxlength'=>'10',
           //'readonly' => 'readonly',
        ), array(
            'label'=>'Gred',
        ), true); ?>                  
                 &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp; &nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;<font style=" color:  #CC0000"> (Contoh: 17 / 41 / JUSA A / TURUS 3) </font>
                 <br> 
            <?php echo tbs_horizontal_dropdown('jenisFasiliti', $jenisFasiliti_u,
        $jenisFasiliti, array(
            'id'=>'jenisFasiliti',
            'class'=>'input-xlarge',
            //'disabled' => 'disabled',
        ), array(
            'label'=>'Jenis Fasiliti',
        ), true)?>  
             
          <div id="ajaxjenisFasiliti">
          <?php echo tbs_horizontal_dropdown('lokasiBertugas', $lokasiBertugas_u,
        $lokasiBertugas, array(
            'id'=>'lokasiBertugas',
            'class'=>'input-xlarge',
            //'disabled' => 'disabled',
        ), array(
            'label'=>'Lokasi Bertugas',
        ), true)?>  
         </div>
          
          <div id="ajaxpenempatan">    
          <?php echo tbs_horizontal_dropdown('penempatan', $penempatan_u,
        $penempatan, array(
            'id'=>'penempatan',
            'class'=>'input-xlarge',
            //'disabled' => 'disabled',
        ), array(
            'label'=>'Penempatan',
        ), true)?>
          </div>     
            
                   <!-- Dropdown Untuk STATUS AKTIF -->        
        <?php echo tbs_horizontal_dropdown('status',$status_u,$status,
                array('id'=>'status','class'=>'',),
                array('label'=>'Status Aktif','class'=>''),
                true);
        ?>
                   <!-- Dropdown Untuk Peranan -->
         <?php echo tbs_horizontal_dropdown('levelAdmin',$levelAdmin_u,$levelAdmin,
                array('id'=>'levelAdmin','class'=>'',),
                array('label'=>'Peranan','class'=>''),
                true);
        ?>
           
       </div>
                
           
       <br>   
        <div class="form-actions">
            <button type="submit" class="btn btn-orange" id="daftar"><i class="icon icon-plus icon-white"></i> Daftar</button>
            <button type="reset" id="semula" class="btn btn-orange"><i class="icon icon-repeat icon-white"></i> Reset</button>
            <a class="btn btn-orange" href="<?php echo base_url('index.php/carian/pengguna')?>"><i class="icon icon-chevron-left  icon-white"></i> Kembali</a>
        </div>

                  
        <?php echo form_close();?>
            
        </div>
        
</div>

<script src='<?php echo base_url('assets/validation/pengguna.js')?>'></script>        

<script>
   // window.listUser = function(){
   //     AjaxCall(base_url+'index.php/pentadbiran/listJson', '', 'listUser', 'id', '', '');
   // };
    
    $(document).ready(function(){
  
     
        $('#simpan').live('click', function() {
           var check_validate = $('#tambah_rekod').valid();
           
           if(check_validate == true){
               
               return true;
           
           }
           
        });
        
            $('#jenisFasiliti').live('change', function(e){
            e.preventDefault();
            $.post(base_url+'index.php/carian/getFasiliti', 'id='+$(this).val(), function(data) {
                if(data == '') {
                    $("#ajaxjenisFasiliti").slideUp('fast').html(data);;
                } else {
                    $("#ajaxjenisFasiliti").html(data).slideDown('fast');
                }
            });
        });
        
        $('#lokasiBertugas').live('change', function(e){
            e.preventDefault();
            $.post(base_url+'index.php/carian/getPenempatan', 'id='+$(this).val(), function(data) {
                if(data == '') {
                    $("#ajaxpenempatan").slideUp('fast').html(data);;
                } else {
                    $("#ajaxpenempatan").html(data).slideDown('fast');
                }
            });
        });

        $("#mykad").blur(function() { //091

            //remove all the class add the messagebox classes and start fading
            $("#msgbox").removeClass().addClass('messagebox').text('semak...').fadeIn("slow");
            //check the username exists or not from ajax

            var val = $("#mykad").val();
            $.post(base_url+'index.php/carian/semakMyKad',{ myKad:val } ,
                    function(data) { //092

                if(data=='yes') { //093
                    $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox
                                            $("#mykad").val("");
                        $(this).html('No. MyKad Telah Wujud').addClass('messageboxerror').fadeTo(900,1);

                    });

                } else {
                    $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox
                                            $("#msgbox").text("");
                    });

                } //093

            }); //092

        });
        
        $("#katalaluan").blur(function() { //091
            
            var password = $("#katalaluan").val();
            var repassword = $("#re_katalaluan").val();
            
            if(password != '' && repassword != '') {
            //remove all the class add the messagebox classes and start fading
            $("#msgbox").removeClass().addClass('messagebox').text('semak...').fadeIn("slow");
            //check the username exists or not from ajax
            
            $.post(base_url+'index.php/carian/semakPassword',{ password:password, repassword:repassword } ,
                    function(data) { //092

                if(data=='yes') { //093
                    $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox
                                            $("#katalaluan").val("");
                                            $("#re_katalaluan").val("");
                        $(this).html('Kata Laluan Dan Pengesahan Kata Laluan Tidak Sepadan').addClass('messageboxerror').fadeTo(900,1);

                    });

                } else {
                    $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox
                                            $("#msgbox").text("");
                    });

                } //093

            });
            
            }

        });
        
        $("#re_katalaluan").blur(function() { //091
            
            var password = $("#katalaluan").val();
            var repassword = $("#re_katalaluan").val();
            
            if(password != '' && repassword != '') {
            //remove all the class add the messagebox classes and start fading
            $("#msgbox").removeClass().addClass('messagebox').text('semak...').fadeIn("slow");
            //check the username exists or not from ajax
            
            $.post(base_url+'index.php/carian/semakPassword',{ password:password, repassword:repassword } ,
                    function(data) { //092

                if(data=='yes') { //093
                    $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox
                                            $("#katalaluan").val("");
                                            $("#re_katalaluan").val("");
                        $(this).html('Kata Laluan Dan Pengesahan Kata Laluan Tidak Sepadan').addClass('messageboxerror').fadeTo(900,1);

                    });

                } else {
                    $("#msgbox").fadeTo(200,0.1,function() {  //start fading the messagebox
                                            $("#msgbox").text("");
                    });

                } //093

            });
            
            }

        });

    });
</script>

2. Put the function below in controllers. Example : controllers/carian.php

<?php
class Carian extends MY_Controller {

    public function __construct() {
        parent::__construct();        
        $this->_ci =& get_instance();
   $this->authentication->check();
$this->load->model('applicant_model');
        $this->load->model("Eminda_model");
        $this->load->model('Tbl_pengguna_model');
        $this->load->model('Tbl_profil_model');
        $this->load->model('Tbl_perkhidmatan_model');
        $this->load->helper('html');
    }
    
    function semakMyKad() {
        
        $myKad  = $this->input->post('myKad');
        if($myKad != '') {
            $data = $this->Eminda_model->semakMyKad($myKad);
            echo $data;
        }

    }
}

3. Put the function below in models. Example : models/eminda_model.php

<?php
class Eminda_model extends CI_Model {
            
function __construct() {
        parent::__construct();

    }

function semakMyKad($myKad) {
            
            $this->db->select('mykad');
            $this->db->where(array('mykad'=>$myKad));
            $query = $this->db->get('pengguna');
            return ($query->num_rows() == 0) ? "no":"yes";
}

}

Di sediakan oleh MOHD AIDIL BIN MOHD NAYAN