Mar
13

MySQL, PHP, Codeigniter, CSS and JQuery working tips.

Following are some useful tips when a developer needs them while developing. Keeping these points in mind will help us to improve our skills.

Codeigniter

Codeigniter is PHP framework which is light weight and very easy to configure and a lot of help available online.
Use separate models for each module so that tracking can be easy.

$this->load->model('Login');

Front and admin should be handled with separate controllers.
Use parser library for loading views.

$this->load->library('parser');	
$data['content'] = $this->parser->parse('site/header', $data, TRUE);

In config folder routes file will help you to create pretty urls.

$route['admin'] = 'admin/index';

Define all your global constants in config/constant.php or create a separate file for this.

// constant.php
define('SITE_NAME', 'zeeshanrasool');

Use flash session for your messages to users.

$this->load->library('session');
// setting data in session
$this->session->set_flashdata('item', 'value');
// using data
$this->session->flashdata('item');

Don’t call any model function inside views as it is not a valid in MVC.
If you want to keep your application folder outside system folder then you need to change path in index.php on main root.

// it is default path
define('BASEPATH', $system_folder.'/');
// change it to 
define('BASEPATH_NEW', '../your_folder/');
// above path will be use like this
define('APPPATH', BASEPATH.$application_folder.'/');

Use rollback functions to keep track the functions otherwise revert all of your actions on failed.

 $this->db->trans_begin();
 if ($this->db->trans_status()===FALSE)
 {
      $this->db->trans_rollback();
      return True;
 } else {
      $this->db->trans_commit();
      return False;
 }

Include all of you css and js files in views separately from controller.
Don’t include all CSS or JS files on single page i-e index.php

PHP

Use switch conditions instead of  if / else in case of using too much conditions. Switch condition is much faster than if / else.

if($a==7)
echo 1;
else if($a==5)
echo 5;

For multiple conditions its best to use switch condition.

switch($a){
  case: 1
  echo 1;
  break;
case:5
  echo 5;
  break;
}

Keep all particular functionality like, code for uploading a file, getting date in specific format etc in separate functions so that you can re-use them instead f writing it again.

Use server side validation for required input fields with client side validation.

Single quotes is faster than double quotes for string or query in quotes.

$query = "Select * from table"; 
$query = 'Select * from table';  // single quoted

Keep error reporting on, so that notices and warnings may be fixed. These small notices may produce some problems on your server online.
Comment your code, what you have done. So next time you are any other developer understand your code easily.
Use .htaccess to put some securities on your code.
Declare all variables properly so that they produce no problem in executions.

MYSQL

Get last 24 hours or 1 day records in mysql.

"select count(*) as cnt from log where date >= 
DATE_SUB(CURDATE(),INTERVAL 1 DAY)";

Export your table to CSV file.

select * into outfile '/file.csv' FIELDS TERMINATED BY ',' OPTIONALLY ENCLOSED BY '"'
LINES TERMINATED BY '\n'
from zips;

Don’t use DISTINCT when you have or could use GROUP BY,
LIMIT m,n may not be as fast as it sounds.
Don’t use ORDER BY RAND() if you have > ~2K records
Avoid using IN(…) when selecting on indexed fields, It will kill the performance of SELECT query.
Minimize traffic by fetching only what you need.
1. Paging/chunked data retrieval to limit
2. Don’t use SELECT *
3. Be wary of lots of small quick queries if a longer query can be more efficient.
Do not duplicate indexes.
Avoid wildcards at the start of LIKE queries.

CSS

Keep css Simple.
Don’t use hacks unless its a known and documented bug.
Take care of margins and padding on all elements.
Avoid using too much absolute positioning.
Validate your code

JQuery

Disable right click.

$(document).ready(function(){
    $(document).bind("contextmenu",function(e){
        return false;
    });
});

Re-size font.

$(document).ready(function(){
  var originalFontSize = $('html').css('font-size');
    $(".resetFont").click(function(){
    $('html').css('font-size', originalFontSize);
  });

Equal height columns.

function equalHeight(group) {
    tallest = 0;
    group.each(function() {
        thisHeight = $(this).height();
        if(thisHeight > tallest) {
            tallest = thisHeight;
        }
    });
    group.height(tallest);
}
/*
Usage:
$(document).ready(function() {
    equalHeight($(".recent-article"));
    equalHeight($(".footer-col"));
});
*/

Remove a word in a text

var el = $('#id');
el.html(el.html().replace(/word/ig, ""));

Preloading images

jQuery.preloadImages = function()
{
  for(var i = 0; i").attr("src", arguments[i]);
  }
};
 
// Usage
$.preloadImages("image1.gif", "/image2.png", "image3.jpg");

Add To Facebook Stumble This Digg This Add To Del.icio.us Add To Reddit Add To Yahoo Add To Twitter


Written by ZeeShaN

ZeeShaN RasooL is a web developer who loves to work in latest technologies to create more interactive dynamic and beautiful web pages.

  • abdul

    thanks…………. a lotZishan

    December 12 2011
    CommentsLike

    • @Zeeshan.
      Thanks for this really helpfull Tutorials.
      This has done a great help to me. Keep doing the great works..
      Once again Thank you for these articles….

      November 07 2011
      CommentsLike

      • [...] We verify Captcha with Ajax in CodeIgniter? Send Email from your Gmail account Using CodeIgniter. MySQL, PHP, CodeIgniter, CSS and JQuery working tips. How to Upload files in CodeIgniter. A simple way for beginner of CI Learn CodeIgniter PHP [...]

        October 31 2011
        CommentsLike
        • ZeeShaN

          thanks :)

          September 02 2011
          CommentsLike
          • IYad

            @Zeeshan,
            IT is Great Website.

            September 02 2011
            CommentsLike
            • ZeeShaN

              Thanks Amol ! I love to work in web development and try my best to share my work with others.

              June 30 2010
              CommentsLike
              • Amol

                Hello Zishan,

                It was a great pleasure reading your articles.

                Also, your site is nice and informative.

                I appreciate you for your hard work and knowledge and mainly for helping others by sharing your knowledge online.

                June 30 2010
                CommentsLike








                Enter your Email:

                Click Here for Popular

                Who I Am

                Zeeshan Rasool

                Software Engineer - PHP
                Lahore - Pakistan

                zeeshan(@)99points.info
                Skype: zeeshan-rasool
                gTalk: zishan.rasool85

                Categories

                Tags

                Comments