Showing posts with label PHP. Show all posts
Showing posts with label PHP. 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. 

Tuesday, 31 October 2017

MENCIPTA KIRAAN HITS CEPAT DAN MUDAH

HITS By CATEGORY

Bagaimana untuk meringkaskan kiraan hits pada kaunter sesebuah laman web?

Saya ringkaskan kepada berikut :

$bulan = date("m");
$tahun = date("Y");
$hariini = date("d");
$semalam= date("Y-m-d", mktime(0, 0, 0, date("m") , date("d")-1,date("Y")));
$mingguini = (Untuk dapatkan sepanjang minggu dari Isnin ke Ahad terkini) seperti berikut :


*****************************************************************
*****************************************************************

Sekian Terima Kasih
Abd Rahman

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

CHECK VALIDITY BETWEEN START DATE & END DATE

1. Put the function below in assets/js/jquery.validate.js

jQuery.validator.addMethod("greaterStart", function (value, element, params) {
    //return this.optional(element) || new Date(value) > new Date($(params).val());
    var check = false;
    if(value >= $(params).val()){
check = true;
} else 
check = false;
return this.optional(element) || check;
},'Tarikh Hingga perlu lebih besar atau sama dengan tarikh Dari');

2. Put the function below in assets/validation/pengaktifan.js

$(document).ready(function(){
    $('#ulangan_kemaskini').validate(
    {
        rules: {
            idAmbilan: {
            minlength: 1,
            number: true,
            required: true
            },
            kodUjian: {
            minlength: 1,
            required: true
            },
            siri: {
            minlength: 1,
            number: true,
            required: true
            },
            tarikhMulaUlang: {
            maxlength: 100,
            required: true
            },
            tarikhAkhirUlang: {
            maxlength: 100,
            required: true,
            greaterStart: '#tarikhMulaUlang'
            },
            statusUjian: {
            minlength: 1,
            required: true
            },
          
        },
        highlight: function(element) {
            $(element).closest('.control-group').removeClass('success').addClass('error');
        },
        success: function(element) {
            element
            .text('OK!').addClass('valid')
            .closest('.control-group').removeClass('error').addClass('success');
        }
    });

});

3. Create date picker fields for start & end date in views. Example : views/pengaktifanUlangan/ujian_ulangan.php

<!--<div class="row-fluid">
    <div class="span12">
        <div class="well">
             Button to trigger modal 
            <a href="#myModal" role="button" class="btn" data-toggle="modal"><i class="icon icon-plus"></i>Tambah</a>
            <a href="<?php echo site_url($this->controller.'/excel'); ?>" class="btn"><i class="icon icon-arrow-down"></i>Muat turun ke excel</a>
            <a href="<?php echo site_url($this->controller.'/pdf'); ?>" class="btn"><i class="icon icon-print"></i>Muat turun ke PDF</a>
        </div>
    </div>
</div>-->



<div class="row-fluid">
    <i><b>Sila klik pada rekod ujian untuk mengaktifkan ujian ulangan atau klik pada bilangan calon untuk melihat senarai calon :</b></i><br>
    <i><b><font style=" color:  #CC0000">Makluman : Pengemaskinian tarikh ulangan hanya boleh dilakukan pada siri ujian yang tarikh tutupnya sudah tamat.</font></b></i>
</div>
<div class="line"></div>
<div id="listUser"></div>
<div id="callback"></div>


<div id="myModalUpdate" class="modal hide fade" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
    <div class="modal-header">
        <button type="button" class="close" data-dismiss="modal" aria-hidden="true">x</button>
        <h3 id="myModalLabel">Kemaskini Ujian Ulangan</h3>
    </div>
    <div class="modal-body">

        <?php echo tbs_horizontal_form_open('', array('id'=>'ulangan_kemaskini'));?>
        
        <?php echo tbs_horizontal_input(array(      //validation using jquery -> assets/validation/register.js
            'name'=>'idAmbilan', 
            'id'=>'idAmbilan',
            'value'=>set_value('idAmbilan', $ulangan['idAmbilan']),
            'class'=>'input-small',
            'maxlength'=>'2',
            'readonly' => 'readonly',
        ), array(
            'label'=>'ID Ambilan',               
        ), true);?>
        
        <?php echo tbs_horizontal_dropdown('kodUjian', $kodUjian_list, $ulangan['kodUjian'],
                array('id'=>'kodUjian','class'=>'','disabled'=>'disabled',),
                array('label'=>'Jenis Ujian','class'=>'',),
                true);
        ?>
        
        <?php echo tbs_horizontal_input(array(      //validation using jquery -> assets/validation/register.js
            'name'=>'siri', 
            'id'=>'siri',
            'value'=>set_value('siri', $ulangan['siri']),
            'class'=>'input-small',
            'maxlength'=>'2',
            'readonly' => 'readonly',
        ), array(
            'label'=>'Siri',               
        ), true);?>        
        
        <?php echo tbs_horizontal_input(array(            
            'name'=>'tarikhMulaUlang',
            'id'=>'tarikhMulaUlang',
            'data-date-format'=>'dd-mm-yyyy',
            'value'=>  set_value('tarikhMulaUlang', $ulangan['tarikhMulaUlang']),
            'class'=>'input-large',
            'maxlength'=>'50',
        ), array(
            'label'=>'Dari',
        ), true); ?>
        
        <?php echo tbs_horizontal_input(array(
            'name'=>'tarikhAkhirUlang',
            'id'=>'tarikhAkhirUlang',
            'data-date-format'=>'dd-mm-yyyy',
            'value'=>  set_value('tarikhAkhirUlang', $ulangan['tarikhAkhirUlang']),
            'class'=>'input-large',
            'maxlength'=>'50',
        ), array(
            'label'=>'Hingga',
        ), true); ?>
        
        <?php echo tbs_horizontal_dropdown('statusUjian',$statusUjian, $ulangan['status'],
                array('id'=>'statusUjian','class'=>'',),
                array('label'=>'Status Ujian','class'=>'',),
                true);
        ?><br>     
        <?php echo form_close();?>    

    </div>
    <div class="modal-footer">
            <button class="btn btn-orange" id="update">Kemaskini</button>
         <button class="btn btn-orange" data-dismiss="modal" aria-hidden="true">Tutup</button>
    </div>          
</div>

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

<script>
    window.listUser = function(){
        AjaxCall(base_url+'index.php/pengaktifanUlangan/listJson_ulangan', '', 'listUser', 'id', '', '');
    };
    
    $(document).ready(function(){
        listUser();
        
          $('#edit').live('click', function () {
            var id = $(this).attr('attr');
            var options = {
                'id' : id
            };
            $.post(base_url+'index.php/pengaktifanUlangan/ulangan_papar', options, function(data) {
                $.each(data, function(key, value){
                    $("#myModalUpdate .modal-body #"+key).val( value );  
                });         
            }, "json");
        });
        
        $('#update').live('click', function() {
           var check_validate = $('#ulangan_kemaskini').valid();
           
           if(check_validate == true){
               
               var $var = "";       //php variable
               $('#ulangan_kemaskini').find(':input').each(function(key, val){   //find all input in form and put in array
                   $var += val.name+"="+val.value+"&";
               });
               
               AjaxCall(base_url+'index.php/pengaktifanUlangan/ulangan_kemaskini', $var, '', '', 'listUser()', 'jAlert');
                             
               $('#myModalUpdate').modal('hide');
           }
           
        });
        
        $('#myModal').on('hide', function(){
              $("#myModal .modal-body input[type='text'], #myModal .modal-body select").val('');
              $("#myModal .modal-body input[type='checkbox']").each(function(){
                  $(this).attr('checked',false);
                  $(this).closest('div').children('div').slideUp('fast').find('input').attr('disabled',true);
              });
          });
          
          $('#tarikhMulaUlang').datepicker({
              //format: 'dd-mm-yyyy',
              autoclose: true,
              startDate: '<?php echo date('d-m-Y') ?>'
          }).on('hide', function(e){
              $(this).valid();
          });
          
          $('#tarikhAkhirUlang').datepicker({
              //format: 'dd-mm-yyyy',
              autoclose: true,
              startDate: '<?php echo date('d-m-Y') ?>'
          }).on('hide', function(e){
              $(this).valid();
          });
    });

</script>

Di sediakan oleh MOHD AIDIL BIN MOHD NAYAN